How to mock service and test POST controller method

Amon Ng :

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

    }

The tests are working for GET and DELETE methods. Could it be that the given weather object in the test doesn't match the actual object created in the controller?

Maciej Kowalski :

You are telling Mockito that you are expecting the exact weather object as an input.

When you call mvc though the object is converted to JSON and then parsed and finally passed to Service as a different instance than you pass to Mockito.

A solution is to use a wildcard as follows:

given(service.createWeather(Mockito.any(Weather.class))).willReturn(createdWeather);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=133355&siteId=1