2 回答

TA貢獻1772條經(jīng)驗 獲得超6個贊
如果您只是想捕獲參數(shù)并以某種方式處理/驗證它們,請不要使用 doAnswer。Mockito 有一個定義的功能,稱為ArgumentCaptor專為此而設(shè)計。通過使用它,您將不需要像您那樣與 void 方法討價還價:
@Mock private MessageProducer messageProducer;
@Captor private ArgumentCaptor<Event> eventCaptor;
@Captor private ArgumentCaptor<Long> longCaptor;
@InjectMocks
private MigrationRequestServiceImpl migrationRequestService;
@Test
public void sendRetriggerRequest() throws Exception {
// When
migrationRequestService.retriggerRequest(emsRetriggerRequest);
// Then
verify(messageProducer).sendMessage(eventCaptor.capture(), longCaptor.capture());
Event e = eventCaptor().getValue();
Long l = longCaptor().getValue();
}

TA貢獻1825條經(jīng)驗 獲得超6個贊
實際上我不想對參數(shù)做任何事情,我只需要跳過這個方法調(diào)用。我只是將 doAnswer 與一些偽代碼一起使用,因為 doNothing() 或 doThrow() 不適用于此方法。
但是我能夠解決這個問題。被注入 Mocks (MigrationRequestServiceImpl) 的類的自動裝配組件 (eventsConfigProperties) 之一沒有在測試類中被模擬!感謝@daniu 指出這一點。
來自 Mockito 的堆棧跟蹤對調(diào)試問題不是很有幫助,它只是在方法調(diào)用時給出了一個空指針異常,這讓我認為可能還有其他問題!
為這個錯誤道歉,我的錯,但謝謝你,很高興知道 ArgumentCaptor,未來測試可能需要它!
必須添加這個自動連接到 MigrationRequestService 類中的條目。
// Test class
@RunWith(MockitoJUnitRunner.class)
public class RetriggerRequestTest {
@Autowired
EventsConfigProperties eventsConfigProperties;
// Other declarations
}
添加回答
舉報