如何模拟服务和测试POST控制器方法

时间:2019-06-18 03:59:40

标签: java spring-boot testing mockito

期望控制器方法返回新创建的天气资源,但响应主体为空。

在调用服务方法时模拟服务以返回天气资源。

发布天气资源的方法:

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

    }

该测试适用于GET和DELETE方法。可能是测试中给定的天气对象与控制器中创建的实际对象不匹配吗?

1 个答案:

答案 0 :(得分:2)

您要告诉Mockito,您希望将确切的weather对象作为输入。

当您调用mvc时,尽管对象已转换为JSON,然后进行了解析,并最终以与传递给Mockito的实例不同的形式传递给Service

一种解决方案是使用通配符,如下所示:

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