mardi 18 août 2015

How Test PUT RestController in Spring Boot

How can I test one PUT request with Spring Boot?? I have this method:

 @RequestMapping(method = RequestMethod.PUT, value = "/")
    public NaturezaTitulo save(@RequestBody NaturezaTitulo naturezaTitulo){
        return naturezaTituloService.save(naturezaTitulo);
    }

and this test class:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
public class NaturezaTituloControllerTest {
    private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
            MediaType.APPLICATION_JSON.getSubtype(),
            Charset.forName("utf8"));

    private MockMvc mockMvc;

    private HttpMessageConverter mappingJackson2HttpMessageConverter;

    private List<NaturezaTitulo> naturezaTituloList = new ArrayList<>();

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Autowired
    void setConverters(HttpMessageConverter<?>[] converters) {

        this.mappingJackson2HttpMessageConverter = Arrays.asList(converters).stream().filter(
                hmc -> hmc instanceof MappingJackson2HttpMessageConverter).findAny().get();

        Assert.assertNotNull("the JSON message converter must not be null",
                this.mappingJackson2HttpMessageConverter);
    }


    @Before
    public void setup() throws Exception {
        this.mockMvc = webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void naturezaTituloNotFound() throws Exception {
        mockMvc.perform(get("/naturezatitulo/55ce2dd6222e629f4b8d6fe0"))
                .andExpect(status().is4xxClientError());
    }

    @Test
    public void naturezaTituloSave() throws Exception {
        NaturezaTitulo naturezaTitulo = new NaturezaTitulo();
        naturezaTitulo.setNatureza("Testando");
        mockMvc.perform(put("/naturezatitulo/").content(this.json(naturezaTitulo))
                .contentType(contentType))
                .andExpect(jsonPath("$.id", notNullValue()));
    }


    protected String json(Object o) throws IOException {
        MockHttpOutputMessage mockHttpOutputMessage = new MockHttpOutputMessage();
        this.mappingJackson2HttpMessageConverter.write(
                o, MediaType.APPLICATION_JSON, mockHttpOutputMessage);
        return mockHttpOutputMessage.getBodyAsString();
    }
}

but I got this error:

java.lang.IllegalArgumentException: json can not be null or empty at com.jayway.jsonpath.internal.Utils.notEmpty(Utils.java:259)

how can I pass one object from body in Put test?

tks

Aucun commentaire:

Enregistrer un commentaire