简体   繁体   中英

java.lang.AssertionError: Content type not set

I'm trying to test a POST and no matter what I do I get the java.lang.AssertionError: Content type not set

My controller:

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

}

and my test:

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

}

And the response of the 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 = []

I already did a question but the error was another, and I could resolve. I don't understand why it's returning 201 created and no content body. Smells like some annotation that I haven't, but I already review with no sucess. Srry about my english and thanks for the help.

EDIT-

I thought the problem was solved but I was wrong

add @ResponseBody on top of controller method.

OR

@PostMapping(produces = {MediaType.APPLICATION_JSON_VALUE} )

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

@PostMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE)

You can add a @RequestMapping annotation to specify the content type in your RestController to the respective method.

Something like:

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

UPDATED :

This newer annotation is a shortcut to the @RequestMapping with RequestMethod.POST :

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

Problem solved, my problem was on the controller 'cause it was returning a void:

My new controller looks like:

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

}

thanks for all

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM