简体   繁体   中英

How to use easymock/powermock mock objects to respond to methods with arguments

I am trying to unit test class Y.

I have an class X

public class X {
    private List<B> getListOfB(List<A> objs) {
    }
}

Now another class Y

public class Y {
    private X x;

    public Z getZ() {
        List<A> aObjs = created inline.
        // I am having problems over here
        List<B> bObjs = x.getListOfB(aObjs);
    }
}

I am trying to test out Y but I can't seem to be get it. So here is what I have so far and I am stuck

@Test
public void testgetZ() {
    X x = createMock(X.class);
    Y y = new Y(x);
    // How do I make this work?
    y.getZ();
}

You need to add expectations on the mock instance of the X class. These expectations will set up the X object to return a list of B objects that can then be tested against.

I also mentioned the use of captures. In EasyMock captures can be used to perform assertions on the objects passed to mocked methods. This is especially useful if (like your example) you cannot provide the instantiated object that is passed to the mocked object.

So I think you want your test to look something like this:

@Test
public void thatYClassCanBeMocked() {
    final X mockX = createMock(X.class);
    final Y y = new Y(mockX);

    //Set up the list of B objects to return from the expectation
    final List<B> expectedReturnList = new List<B>();

    //Capture object for the list Of A objects to be used in the expectation
    final Capture<List<A>> listOfACapture = new Capture<List<A>>();

    //expectation that captures the list of A objects provided and returns the specified list of B objects
    EasyMock.expect( mockX.getListOfB( EasyMock.capture(listOfACapture) ) ).andReturn(expectedReturnList);

    //Replay the mock X instance
    EasyMock.replay(mockX);

    //Call the method you're testing
    final Z = y.getZ();

    //Verify the Mock X instance
    EasyMock.verify(mockX);

    //Get the captured list of A objects from the capture object
    List<A> listOfA = listOfACapture.getValue();

    //Probably perform some assertions on the Z object returned by the method too.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM