【问题标题】:java.lang.AssertionError: Content type not setjava.lang.AssertionError:未设置内容类型
【发布时间】:2018-07-12 12:26:30
【问题描述】:

我正在尝试测试 POST,但无论我做什么,我都会收到 java.lang.AssertionError: Content type not set

我的控制器:

@RestController
@RequestMapping("/artistas")

public class ArtistaEndpoint {

    private final ArtistaService artistaService;
    private final ArtistaMapper artistaMapper;
    private final AlbumService albumService;

    @CrossOrigin(origins = "http://localhost:8080")
    @PostMapping
    public ResponseEntity<Void> post(@Valid @RequestBody Artista artista) { 

        artista = artistaService.save(artista);

        ArtistaDto artistaDto = artistaMapper.toDtoCompleto(artista);
        URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(artistaDto.getId()).toUri();

        if(!artista.getAlbuns().isEmpty()) {
            Set<Album> albuns = artista.getAlbuns();
            for(Album album: albuns) {
                album.setArtista(artista);
                albumService.save(album);
            }
        }

        return ResponseEntity.created(uri).build();
    }

}

和我的测试:

    @Test
public void salvarArtistaSemAlbum() throws Exception {

    Artista adicionado = new Artista();
    adicionado.setId(1L);
    adicionado.setNome("Banda Eva");
    adicionado.setDescricao("Viva o carnaval");

    when(artistaService.save(Mockito.any(Artista.class))).thenReturn(adicionado);

    mockMvc.perform(MockMvcRequestBuilders.post("/artistas")
            .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
            .accept(MediaType.APPLICATION_JSON_UTF8_VALUE)and 
            .content(TestUtil.asJsonString(adicionado)))

            .andExpect(status().isCreated())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))

            .andExpect(jsonPath("$.id", is(1)))
            .andExpect(jsonPath("$.nome", is("Banda Eva")))
            .andExpect(jsonPath("$.descricao", is("Viva o carnaval")));

    verify(artistaService, times(1)).save(Mockito.any(Artista.class));
    verifyNoMoreInteractions(artistaService);
    assertNull(adicionado.getId());
    assertThat(adicionado.getNome(), is("Banda Eva"));
    assertThat(adicionado.getDescricao(), is("Viva o carnaval"));

}

以及httpservlet的响应:

    MockHttpServletResponse:
           Status = 201
    Error message = null
          Headers = {Location=[http://localhost/artistas/1]}
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = http://localhost/artistas/1
      Cookies = []

我已经做了一个问题,但错误是另一个问题,我可以解决。我不明白为什么它返回 201 created 并且没有内容正文。闻起来像一些我没有的注释,但我已经复习了,但没有成功。 对我的英语感到抱歉,感谢您的帮助。

编辑-

我以为问题解决了,但我错了

【问题讨论】:

  • 为什么要返回带有内容的正文?你正在返回Void aka,什么都没有......没有什么可以返回,也没有什么没有内容类型。所以要么显式设置内容类型,要么实际设置正文。

标签: java spring spring-mvc junit spring-test


【解决方案1】:

您可以直接在 PostMapping 注释中添加内容类型:

@PostMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE)

【讨论】:

    【解决方案2】:

    在控制器方法的顶部添加@ResponseBody

    @PostMapping(produces = {MediaType.APPLICATION_JSON_VALUE} )
    

    【讨论】:

    • 方法上添加注解
    • 抱歉错字..我的意思是 ResponseBody 但这不是你所需要的,因为你用 RestController 进行了注释..所以尝试产生解决方案
    【解决方案3】:

    您可以添加@RequestMapping 注释以将RestController 中的内容类型指定给相应的方法。

    类似:

    @RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.POST).

    更新

    这个较新的注释是@RequestMappingRequestMethod.POST 的快捷方式:

    @PostMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes=MediaType.APPLICATION_JSON_UTF8_VALUE)
    

    【讨论】:

    • 请注意,如果RestController 也期望接收该内容类型,您还应该设置consumes 属性,而不仅仅是produces
    【解决方案4】:

    问题解决了,我的问题出在控制器上,因为它返回一个 void:

    我的新控制器如下所示:

    public class ArtistaEndpoint {
    
    private final ArtistaService artistaService;
    private final ArtistaMapper artistaMapper;
    private final AlbumService albumService;
    
    @CrossOrigin(origins = "http://localhost:8080")
    @PostMapping
    public ResponseEntity<ArtistaDto> post(@Valid @RequestBody Artista artista) { 
    
        artista = artistaService.save(artista);
    
        ArtistaDto artistaDto = artistaMapper.toDtoCompleto(artista);
        URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(artistaDto.getId()).toUri();
    
        if(!artista.getAlbuns().isEmpty()) {
            Set<Album> albuns = artista.getAlbuns();
            for(Album album: albuns) {
                album.setArtista(artista);
                albumService.save(album);
            }
        }
    
        return ResponseEntity.created(artistaDto).body();
    }
    

    }

    谢谢大家

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-26
      • 2017-03-09
      • 1970-01-01
      相关资源
      最近更新 更多