【问题标题】:How to use easymock/powermock mock objects to respond to methods with arguments如何使用 easymock/powermock 模拟对象响应带参数的方法
【发布时间】:2014-07-17 15:58:58
【问题描述】:

我正在尝试对 Y 类进行单元测试。

我有一个 X 课

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

现在是另一个班级

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();
}

【问题讨论】:

  • 我不清楚你到底想达到什么目的?也许你可以再澄清一点。

标签: java junit easymock powermock


【解决方案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.
}

【讨论】:

  • 我也想投票!太棒了,谢谢!
  • 不用担心。在回答你的问题时,我实际上发现最新版本的 EasyMock 也可以通过注释来做事。看看documentation for this,它更详细地解释了这一点,但它看起来很漂亮。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-19
相关资源
最近更新 更多