首页 > 解决方案 > Junit java.lang.AssertionError:JSON 路径“$.reward”

问题描述

我有一个提供的测试方法,

@Test
    public void calculateReward() throws Exception {

        when(userService.findById(any(Long.class))).thenReturn(Optional.of(user));
        int steps = 1000;

        user.setCurrentSteps(steps);
        user.setTotalSteps(steps);

        when(userService.save(any(User.class))).thenReturn(user);
        Map<String, Double> map = new HashMap<>();
        map.put("EUR", 1.0);
        when(currencyUtilities.getCurrencyMap()).thenReturn(map);

        mockMvc.perform(put("/api/v1/users/calculateReward")
                .param("userId", String.valueOf(user.getId())))
                .andExpect(
                        status().isCreated()
                ).andExpect(
                content().contentType(MediaType.APPLICATION_JSON_UTF8)
        ).andDo(print())
                .andExpect(
                        jsonPath("$.name", is(user.getName()))
                ).andExpect(
                jsonPath("$.currency", is(user.getCurrencyName()))
        ).andExpect(
                jsonPath("$.reward", is(1.0)));
    }

我收到错误消息,

java.lang.AssertionError: JSON path "$.reward"
Expected: is <1.0>
     but: was "1.00"
Expected :is <1.0>
Actual   :"1.00"

这里有什么问题?

标签: javajunit

解决方案


正如错误消息所说:测试期望在它接收到的 JSON 中看到数字 1.0 ( is(1.0)),但 JSON 实际上包含该"1.00"路径中的字符串。阅读https://github.com/json-path/JsonPath了解路径的含义,但$.reward只是"reward"根对象的字段。所以它应该看起来像

{
  "reward": 1.0,
  ... other fields including "name" and "currency"
}

但是是

{
  "reward": "1.00",
  ...
}

推荐阅读