![](/img/trans.png)
[英]How to verify if method was called from other with same class by mockito
[英]Mockito, how to verify if the method of the tested class was called?
我想檢查方法執行期間是否調用了 toDishResponseDTO。 但這是不可能的,因為這是正在測試的 class 的方法。 如何才能做到這一點?
Class
@ExtendWith(MockitoExtension.class)
class DishServiceTest {
@Mock
DishRepository dishRepository;
@Mock
RestaurantRepository restaurantRepository;
@Autowired
@InjectMocks
DishService dishService;
待測方法
public List<DishResponseDTO> getAll() {
List<Dish> dishlsit = dishRepository.findAll();
return dishlsit.stream()
.map(this::toDishResponseDTO)
.collect(Collectors.toList());
}
測試
@Test
void shouldCallFindAllReturnDto_whenV() {
Mockito.when(dishRepository.findAll()).thenReturn(TestData.ENTITY_DISH);
dishService.getAll();
Mockito.verify(dishRepository, times(1)).findAll();
Mockito.verify(dishService times(6)).toDishResponseDTO(any()); // compile error, because verify can be called only on mocks
}
您將無法使用 Mockito 來驗證該方法是否被調用,但您可以從getAll()
方法驗證 output,前提是您已經模擬了對dishRepository.findAll()
的響應。 因此,實際上,只需在將預期數據與實際數據相匹配的驗證調用之后添加一些斷言,我假設this::toDishResponseDTO
只返回一個Dish
。
@Test
void shouldCallFindAllReturnDto_whenV() {
Mockito.when(dishRepository.findAll()).thenReturn(TestData.ENTITY_DISH);
List<Dish> dishes = dishService.getAll();
Mockito.verify(dishRepository, times(1)).findAll();
assertThat(dishes, is(notNullValue());
assertThat(dishes.get(0).getSomeField, is(equalTo("someValue")));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.