gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 12:45:59 24 4
gpt4 key购买 nike

我正在尝试对 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.
}

关于java - 如何使用easymock/powermock模拟对象响应带参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24706108/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com