lundi 17 juin 2019

How to mock service and test POST controller method

Expecting the controller method to return the newly created weather resource, but the response body is empty.

Mocked the service to return a weather resource when the service method is called.

POST method for weather resource:

    @ApiOperation("Creates a new weather data point.")
    public ResponseEntity<Weather> createWeather(@Valid @RequestBody Weather weather) {     
        try {
            Weather createdWeather = weatherService.createWeather(weather);

            return ResponseEntity.ok(createdWeather);
        } catch(SQLException e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

Test:

    @Test
    public void createWeather_200() throws Exception {
        Weather weather = new Weather(null, "AC", new Date(1560402514799l), 15f, 10, 2);
        Weather createdWeather = new Weather(1, "AC", new Date(1560402514799l), 15f, 10, 2);

        given(service.createWeather(weather)).willReturn(createdWeather);

        MvcResult result = mvc.perform(post("/weather")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(weather)))
        .andExpect(status().isOk())
                .andExpect(jsonPath("$['id']", is(createdWeather.getId())));

    }

Aucun commentaire:

Enregistrer un commentaire