【发布时间】:2017-07-07 12:16:21
【问题描述】:
我有这样的事情:
public interface SomeInterface {
public String someMethod(String someArg1, String someArg2);
}
public class SomeInterfaceImpl {
@Override
public String someMethod(String someArg1, String someArg2) {
String response;
// a REST API call which fetches response (need to mock this)
return response;
}
}
public class SomeClass {
public int execute() {
int returnValue;
// some code
SomeInterface someInterface = new SomeInterfaceImpl();
String response = someInterface.someMethod("some1", "some2");
// some code
return returnValue;
}
}
我想使用 JUnit 测试 SomeClass 中的 execute() 方法。由于someMethod(String someArg1, String someArg2) 调用了一个REST API,我想模拟someMethod 以返回一些预定义的响应。但不知何故,真正的someMethod 被调用而不是返回预定义的响应。如何让它发挥作用?
这是我尝试使用 Mockito 和 PowerMockito 的方法:
@RunWith(PowerMockRunner.class)
@PrepareForTest({ SomeInterface.class, SomeInterfaceImpl.class, SomeClass.class })
public class SomeClassTest {
@Test
public void testExecute() {
String predefinedResponse = "Some predefined response";
int expectedReturnValue = 10;
SomeInterfaceImpl impl = PowerMockito.mock(SomeInterfaceImpl.class);
PowerMockito.whenNew(SomeInterfaceImpl.class).withAnyArguments().thenReturn(impl);
PowerMockito.when(impl.someMethod(Mockito.any(), Mockito.any())).thenReturn(predefinedResponse);
SomeClass someClass = new SomeClass();
int actualReturnValue = someClass.execute();
assertEquals(expectedReturnValue, actualReturnValue);
}
}
【问题讨论】:
-
这正是引入依赖注入的地方。不要使用
new,将SomeInterface作为参数传递。 -
@AndyTurner 我试过
SomeInterface interface = PowerMockito.mock(SomeInterface.class),然后是PowerMockito.when(interface.someMethod(Mockito.any(), Mockito.any())).thenReturn(predefinedResponse);。它导致了同样的问题。 -
@AndyTurner:看过相关问题。如果你看到我的测试,我已经处理好了。
标签: java unit-testing junit mockito powermockito