简体   繁体   English

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

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

I am trying to unit test class Y. 我正在尝试对Y类进行单元测试。

I have an class X 我有X班

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

Now another class Y 现在是另一个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. 我正在尝试测试Y,但似乎无法理解。 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. 您需要在X类的模拟实例上添加期望。 These expectations will set up the X object to return a list of B objects that can then be tested against. 这些期望将设置X对象以返回可以测试的B对象的列表。

I also mentioned the use of captures. 我还提到了捕获的使用。 In EasyMock captures can be used to perform assertions on the objects passed to mocked methods. 在EasyMock中,捕获可用于对传递给模拟方法的对象执行断言。 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.
}

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

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