問題描述
例如我有處理程序:
@Component
public class MyHandler {
@AutoWired
private MyDependency myDependency;
public int someMethod() {
...
return anotherMethod();
}
public int anotherMethod() {...}
}
為了測試它,我想寫這樣的東西:
to testing it I want to write something like this:
@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);
}
}
但每當(dāng)我嘗試模擬它時,它實(shí)際上都會調(diào)用 anotherMethod()
.我應(yīng)該用 myHandler
做什么來模擬它的方法?
But it actually calls anotherMethod()
whenever I try to mock it. What should I do with myHandler
to mock its methods?
推薦答案
首先mock MyHandler方法的原因可能如下:我們已經(jīng)測試過anotherMethod()
,它的邏輯很復(fù)雜,那么,如果我們可以verify
它正在調(diào)用,為什么我們需要再次測試它(就像 someMethod()
的一部分)?
我們可以通過:
First of all the reason for mocking MyHandler methods can be the following: we already test anotherMethod()
and it has complex logic, so why do we need to test it again (like a part of someMethod()
) if we can just verify
that it's calling?
We can do it through:
@RunWith(MockitoJUnitRunner.class)
class MyHandlerTest {
@Spy
@InjectMocks
private MyHandler myHandler;
@Mock
private MyDependency myDependency;
@Test
public void testSomeMethod() {
doReturn(1).when(myHandler).anotherMethod();
assertEquals(myHandler.someMethod() == 1);
verify(myHandler, times(1)).anotherMethod();
}
}
注意:在 'spying' 對象的情況下,我們需要使用 doReturn
而不是 thenReturn
(小解釋是 這里)
Note: in case of 'spying' object we need to use doReturn
instead of thenReturn
(little explanation is here)
這篇關(guān)于如何模擬 @InjectMocks 類的方法?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!