如何使用easymock / powermock模拟对象来响应带参数的方法

时间:2014-07-11 20:34:43

标签: java junit easymock powermock

我正在尝试单元测试Y类。

我有一个X类

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

现在另一个班级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);
    }
}

我试图测试Y但我似乎无法得到它。所以这就是我到目前为止所遇到的问题

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

1 个答案:

答案 0 :(得分:1)

您需要在X类的模拟实例上添加期望值。这些期望将设置X对象以返回B对象的列表,然后可以对其进行测试。

我还提到了捕获的使用。在EasyMock中,捕获可用于对传递给模拟方法的对象执行断言。如果(如您的示例)您无法提供传递给模拟对象的实例化对象,则此功能特别有用。

所以我认为你希望你的测试看起来像这样:

@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.
}