【发布时间】:2015-08-26 18:27:14
【问题描述】:
例如我有处理程序:
@Component
public class MyHandler {
@AutoWired
private MyDependency myDependency;
public int someMethod() {
...
return anotherMethod();
}
public int anotherMethod() {...}
}
为了测试它,我想写这样的东西:
@RunWith(MockitoJUnitRunner.class}
class MyHandlerTest {
@InjectMocks
private MyHandler myHandler;
@Mock
private MyDependency myDependency;
@Test
public void testSomeMethod() {
when(myHandler.anotherMethod()).thenReturn(1);
assertEquals(myHandler.someMethod() == 1);
}
}
但每当我尝试模拟它时,它实际上都会调用anotherMethod()。我应该如何处理 myHandler 来模拟它的方法?
【问题讨论】:
-
如果你想测试 MyHandler,你不应该模拟它自己的方法(因为你想测试你的处理程序,而不是模拟)。您是否需要这样做的具体原因?
标签: java unit-testing mocking mockito