gpt4 book ai didi

java - EasyMock:无效方法

转载 作者:IT老高 更新时间:2023-10-28 13:51:39 26 4
gpt4 key购买 nike

我有一个方法在一个类中返回 void,该类是我要测试的类的依赖项。

这个类很大,我只使用其中的一个方法。我需要为测试替换此方法的实现,因为我希望它做一些不同的事情,并且我需要能够访问此方法接收的参数。

我在 EasyMock 中找不到这样做的方法.我想我知道如何使用 Mockito通过使用 doAnswer但除非绝对必要,否则我不想添加另一个库。

最佳答案

如果我理解您想要正确执行的操作,您应该可以使用 andAnswer():

mockObject.someMethod(eq(param1), eq(param2));
expectLastCall().andAnswer(new IAnswer() {
public Object answer() {
//supply your mock implementation here...
SomeClass arg1 = (SomeClass) getCurrentArguments()[0];
AnotherClass arg2 = (AnotherClass) getCurrentArguments()[1];
arg1.doSomething(blah);
//return the value to be returned by the method (null for void)
return null;
}
});

EasyMock User Guide解释:

Creating Return Values or Exceptions

Sometimes we would like our mock object to return a value or throw an exception that is created at the time of the actual call. Since EasyMock 2.2, the object returned by expectLastCall() and expect(T value) provides the method andAnswer(IAnswer answer) which allows [you] to specify an implementation of the interface IAnswer that is used to create the return value or exception.

Inside an IAnswer callback, the arguments passed to the mock call are available via EasyMock.getCurrentArguments(). If you use these, refactorings like reordering parameters may break your tests. You have been warned.

关于java - EasyMock:无效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/859031/

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