![](/img/trans.png)
[英]Mockito, how to verify if the method of the tested class was called?
[英]Is it possible to verify tested object method call with Mockito?
我有一些業務邏輯課:
public class SomeService {
public void doFirst() {}
public void doSecond() {
doFirst();
}
}
並測試:
public class SomeServiceTest {
private SomeService service;
@Before
public void setUp() {
service = new SomeService();
}
@Test
public void doSecond_someCondition_shouldCallFirst() {
// given
...
// when
service.doSecond();
//then
how to verify doFirst() was called?
}
}
如何驗證doFirst()不是在模擬中調用,而是在真實服務中調用?
我想知道為什么要測試,被測方法調用什么方法。 聽起來很像白盒測試。
在我看來,您想驗證調用的結果而不是驗證到達結果的方法,因為這很容易改變(即在重構時)。
因此,如果doSecond()的結果與doFirst()相同,則可以為doFirst()編寫一個測試,並使用相同的測試(即一組斷言)來測試doSecond()。
但是,如果您真的要測試,則doSecond()是否已調用doFirst(),則可以將服務包裝在間諜程序中,然后在間諜程序上調用驗證:
//given
SomeService service = new SomeService();
SomeService spy = Mockito.spy(service);
//when
spy.doSecond();
//then
verify(spy).doFirst();
聽起來您想避免在測試中調用真正的doFirst嗎? 如果是這樣,請嘗試...
//given
boolean firstCalled = false;
SomeService fakeService = new SomeService {
@Override
public void doFirst() {
firstCalled = true;
}
}
//when
fakeService.doSecond();
// then
assertTrue(firstCalled);
出於明顯的原因,這種測試/模擬技術被稱為“子類和替代”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.