I want to test this method:
@Override
public GenreResponse fetchGenreById(Long genreId) {
return convertGenreToGenreResponse(findGenreEntityByGenreId(genreId));
}
private GenreResponse convertGenreToGenreResponse(Genre genre) {
return modelMapper.map(genre, GenreResponse.class);
}
private Genre findGenreEntityByGenreId(long genreId) {
return genreRepository.findByGenreId(genreId)
.orElseThrow(() -> new ObjectNotFoundException("Genre with " + genreId + " id not found!"));
}
I wrote a test for this method, but it doesn’t work, and I can’t figure out why.
This is my test:
@ExtendWith(MockitoExtension.class)
class GenreCrudServiceTest {
@Mock
private ModelMapper mockModelMapper;
@Mock
private GenreRepository mockGenreRepository;
private GenreCrudService genreCrudService;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
genreCrudService = new GenreCrudServiceImpl(mockModelMapper, mockGenreRepository);
}
@Test
public void GenreCrudService_FetchGenreById_ReturnsGenreResponse() {
// Arrange
long genreId = 1;
Genre genre = Genre.builder()
.genreId(genreId)
.title("testTitle")
.build();
Mockito.when(mockGenreRepository.findByGenreId(any(Long.class))).thenReturn(Optional.of(genre));
// Act
GenreResponse genreResponse = genreCrudService.fetchGenreById(genreId);
// Assert
Assertions.assertThat(genreResponse).isNotNull();
}
But my test doesn’t work, it gives me an error:
Expecting actual not to be null
java.lang.AssertionError:
Expecting actual not to be null
The error occurs on this line:
Assertions.assertThat(genreResponse).isNotNull();
I can’t figure out why I’m getting null returned, because here I’ve defined:
Mockito.when(mockGenreRepository.findByGenreId(any(Long.class))).thenReturn(Optional.of(genre));
that when searching for a genre by id, a specific Genre will be returned, and further method should convert it to GenreResponse
New contributor
Denis Lebenkov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.