【问题标题】:JUnit RestControllerTest for @PutMapping throws InvocationTargetException@PutMapping 的 JUnit RestControllerTest 抛出 InvocationTargetException
【发布时间】:2020-09-14 12:14:52
【问题描述】:

我正在使用 Spring Boot 构建一个微服务。我使用 GET-、POST-、PUT-、DELETE- 方法编写了一个 API,运行该应用程序并使用 Postman 对其进行了测试 - 一切正常...

但是测试 PUT 方法失败了

java.lang.AssertionError:预期状态: 但原为:

在调试模式下运行测试并单步抛出 InvocationTargetException:

我的 RestController-Methods 如下所示:

@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));
}

SongRepository 只是一个扩展 JpaRepository 的简单接口。

我的失败测试如下所示:

@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());
}

而 getValidSongDto() 只是提供了一个在我的测试中使用的 Dto:

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

我现在真的不明白,我做错了什么导致这个测试失败,而且到目前为止在互联网上也找不到任何可以帮助我解决这个问题的东西。因此,如果有人能告诉我这里出了什么问题以及如何解决这个问题,我将非常感激。

非常感谢!!

【问题讨论】:

  • 您没有为 songService.getSongById 定义任何内容,这会导致 null 响应并导致 400 错误。实际上这永远不会发生,因为会抛出异常。话虽这么说,你的反应也很奇怪,你给了状态NO_CONTENT,但你包含了内容。

标签: java spring spring-boot mockito invocationtargetexception


【解决方案1】:

您需要返回songService.getSongById 的值,如下所示

@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());
}

【讨论】:

  • 非常感谢。效果很好——我的测试现在很开心,我也很开心。
  • @Mahakala108,你可以接受答案,这样别人就会知道答案被接受了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-11
  • 2017-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-13
相关资源
最近更新 更多