繁体   English   中英

如何使用Easymock / Powermock模拟对象响应带参数的方法

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

我正在尝试对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();
}

您需要在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.
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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