Issue
I want to check if toDishResponseDTO was called during a method execution. But it's not possible since this is a method of the class being tested. How can this be done?
Class
@ExtendWith(MockitoExtension.class)
class DishServiceTest {
@Mock
DishRepository dishRepository;
@Mock
RestaurantRepository restaurantRepository;
@Autowired
@InjectMocks
DishService dishService;
Method under test
public List<DishResponseDTO> getAll() {
List<Dish> dishlsit = dishRepository.findAll();
return dishlsit.stream()
.map(this::toDishResponseDTO)
.collect(Collectors.toList());
}
Test
@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
}
Solution
You won't be able to use Mockito to verify that method is called, but you can verify the output from the getAll()
method given that you've mocked out the response to dishRepository.findAll()
. So, in effect, just add some assertions after your verify calls that match your expected data with the actual data, I assume that this::toDishResponseDTO
just return a 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")));
}
Answered By - lane.maxwell
Answer Checked By - Timothy Miller (JavaFixing Admin)