Junit java.lang.AssertionError:JSON路径“ $ .reward”

时间:2019-04-14 16:16:27

标签: java junit

我提供了一种测试方法

@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"

这是什么问题?

1 个答案:

答案 0 :(得分:1)

就像错误消息所表明的那样:测试期望在接收到的JSON(is(1.0)中看到数字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",
  ...
}