Mockito,如何验证是否调用了被测class的方法?

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() 方法的输出,前提是您已经模拟了对 dishRepository.findAll() 的响应.因此,实际上,只需在您的验证调用之后添加一些断言,使您的预期数据与实际数据相匹配,我假设 this::toDishResponseDTO 只是 return 一个 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")));
}