![](/img/trans.png)
[英]Mockito - 0 Matchers Expected, 2 Recorded (InvalidUseOfMatchersException)
[英]InvalidUseOfMatchersException with mockito using matchers
我正在使用Mockito,並且遇到了下一個問題:
java.lang.AssertionError:
Expected: (an instance of java.lang.IllegalArgumentException and exception with message a string containing "")
but: an instance of java.lang.IllegalArgumentException <org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
0 matchers expected, 1 recorded:
-> at com.rccl.middleware.kidsclub.engine.services.KidServiceTest.saveKid_kidExist_throwException(KidServiceTest.java:97)
This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));
這是我的測試代碼:
@Mock
private KidRepository kidRepository;
@Mock
private RoomService roomService;
@Test
public void saveKid_kidExist_throwException() {
given(kidRepository.existsById(anyString())).willReturn(true);
given(roomService.existShipRoomDefault()).willReturn(true);
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage(startsWith("Kid already registered"));
KidDTO kidDTO = MockDTO.buildKidDTO();
service.saveKid(kidDTO);
then(kidRepository).should().existsById(anyString());
}
這是saveKid方法的代碼,該方法基本上發送異常:
if (!validateShipRoomExist()) {
log.warn("::: The ShipRoom document doesn't exist.");
throw new RoomNotFoundException(NO_ROOMS_IN_DATABASE);
}
if (validateKidAlreadyRegistered(kidDTO.getId())) {
log.warn("::: Trying to persist a Kid already persisted with ID [{}]", kidDTO.getId());
throw new IllegalArgumentException(String.format("Kid already registered with ID [%s]", kidDTO.getId()));
}
這些方法稱為:
private boolean validateShipRoomExist() {
return roomService.existShipRoomDefault();
}
public boolean validateKidAlreadyRegistered(@NotNull String kidId) {
return kidRepository.existsById(kidId);
}
接下來是我在roomService中的代碼:
public boolean existShipRoomDefault() {
return roomRepository.existsById(DEFAULT_AGGREGATOR_ID);
}
問題在於此方法存在問題,即使我在此測試中使用字符串anyString()也不例外。 我不知道在這種情況下發生了什么。 一個有趣的想法是,在調試模式下,如果有斷點,測試不會失敗。
BDDMockito.startsWith
是一個匹配器方法,你所使用的expectedException.expectMessage
這是無關的嘲諷。
如果要評估異常消息,則應將其與完整消息進行比較。
經過調整的測試可能如下所示:
@Test
public void saveKid_kidExist_throwException() {
// ...
KidDTO kidDto = new KidDTO();
kidDto.setId("1");
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Kid already registered with ID [1]");
service.saveKid(kidDto);
}
因為我不知道MockDTO類在做什么,並且我認為可以很容易地自己創建KidDTO
實例, KidDTO
我只是在上面的示例中這樣做。
一個替代方案是-如果kidDTO
是模擬的-定義:
BDDMockito.given(kidDto.getId()).willReturn("1");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.