JUnit RestControllerTest per @PutMapping genera InvocationTargetException

Sep 14 2020

Sto creando un microservizio utilizzando Spring Boot. Ho scritto un'API con i metodi GET-, POST-, PUT-, DELETE-, ho eseguito l'applicazione e l'ho testata utilizzando Postman: tutto funziona bene ...

Ma il test del metodo PUT fallisce con

java.lang.AssertionError: stato previsto: <204> ma era: <400>

L'esecuzione del test in modalità debug e l'esecuzione di passaggi genera un'eccezione InvocationTargetException:

I miei metodi RestController hanno questo aspetto:

@PutMapping(value = "/{id}")
public ResponseEntity updateSongById(@PathVariable("id") Integer id, @RequestBody @Validated 
SongDto songDto) {
    // TODO Add authorization
    SongDto song = songService.getSongById(id);
    if (song == null)
        return new ResponseEntity(HttpStatus.BAD_REQUEST);
    return new ResponseEntity(songService.updateSong(id, songDto), HttpStatus.NO_CONTENT);
}

songService.getSongById (id):

@Override
public SongDto getSongById(Integer id) {
    return songMapper.songToSongDto(songRepository.findById(id)
        .orElseThrow(NotFoundException::new));
}

Il SongRepository è solo una semplice interfaccia che estende JpaRepository <Song, Integer>.

Il mio test fallito è simile a questo:

@Test
void updateSongById_success() throws Exception {
    when(songService.updateSong(anyInt(), any(SongDto.class))).thenReturn(getValidSongDto());
    String songDtoJson = objectMapper.writeValueAsString(getValidSongDto());
    mockMvc.perform(put("/rest/v1/songs/1")
            .content(songDtoJson)
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isNoContent());
}

E getValidSongDto () fornisce solo un Dto utilizzato nei miei test:

private SongDto getValidSongDto() {
    return SongDto.builder()
            .id(1)
            .title("TestSongValid")
            .label("TestLabelValid")
            .genre("TestGenreValid")
            .artist("TestArtistValid")
            .released(1000)
            .build();
}

Al momento non capisco davvero cosa ho sbagliato per far fallire questo test e inoltre non sono riuscito a trovare nulla su Internet che mi abbia aiutato a risolvere questo problema, finora. Quindi, per questo sarei molto grato se qualcuno potesse dirmi cosa c'è che non va qui e come risolvere questo problema.

Grazie mille!!

Risposte

2 SSK Sep 14 2020 at 21:02

È necessario restituire il valore per songService.getSongByIdcome mostrato di seguito

@Test
void updateSongById_success() throws Exception {
    
    when(songService.getSongById(Mockito.any())).thenReturn(getValidSongDto());
    
    when(songService.updateSong(anyInt(), any(SongDto.class))).thenReturn(getValidSongDto());
    
    String songDtoJson = objectMapper.writeValueAsString(getValidSongDto());
    
    mockMvc.perform(put("/rest/v1/songs/1")
            .content(songDtoJson)
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isNoContent());
}