java.lang.AssertionError : No value at JSON path

标签 java junit jsonpath

我运行一个单元测试,我想获取一个 JSON 对象并需要将其与值进行比较。下面提供了终点,

private static final String TOTAL_REWARD = "total_reward_";
private static final String EUR = "EUR";

@GetMapping(value = "/findUsersPayouts")
    public ResponseEntity<String> findUsersPayoutList(@RequestParam("userId") Long userId) {

        Optional<User> optional = userService.findById(userId);

        if (!optional.isPresent()) {
            return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
        }

        User user = optional.get();

        List<Reward> rewards = user.getRewards();


        JSONObject obj = new JSONObject();

        obj.put("id", user.getId());
        obj.put("name", user.getName());

        JSONArray array = new JSONArray();

        for (Reward reward : rewards) {

            JSONObject currData = new JSONObject();

            double amount = reward.getAmount();
            String currencyName = user.getCurrencyName();

            Map<String, Double> currencyMap = currencyUtilities.getCurrencyMap();

            currData.put(TOTAL_REWARD + EUR, amount);


            /*
             * convert the reward amount to 2 decimals limit
             * */
            DecimalFormat df = new DecimalFormat("#.00");

            double rewardInLocalCurrency = amount * currencyMap.get(currencyName);
            String rewd = df.format(rewardInLocalCurrency);

            currData.put(TOTAL_REWARD + currencyName, rewd);
            array.put(currData);
        }

        obj.put("rewards", array);
        return ResponseEntity.status(HttpStatus.CREATED).contentType(MediaType.APPLICATION_JSON_UTF8).body(obj.toString());
    }

我这里有测试,

@Test
    public void findUsersPayoutList() throws Exception {

        when(userService.findById(any(Long.class))).thenReturn(Optional.of(user));

        Reward reward = new Reward();
        reward.setUser(user);
        reward.setId(55L);
        reward.setAmount(1);

        Reward reward1 = new Reward();
        reward1.setUser(user);
        reward1.setId(57L);
        reward1.setAmount(1);

        user.addReward(reward);
        user.addReward(reward1);

        Map<String, Double> map = new HashMap<>();
        map.put("EUR", 1.0);

        when(currencyUtilities.getCurrencyMap()).thenReturn(map);
        JSONArray rewards = new JSONArray();
        JSONObject object = new JSONObject();
        object.put("total_reward_EUR :", 1);

        rewards.put(object);
        rewards.put(object);

        mockMvc.perform(get("/api/v1/users/findUsersPayouts").param("userId", String.valueOf(user.getId())))
                .andExpect(
                        status().isCreated()
                ).andExpect(
                content().contentType(MediaType.APPLICATION_JSON_UTF8)
        ).andDo(print())
                .andExpect(
                        jsonPath("$.id", is(user.getId().intValue()))
                ).andExpect(
                jsonPath("$.name", is(user.getName()))
        ).andExpect(
                jsonPath("$.rewards[0].['total_reward_EUR :']", is("1.00"))
        ).andExpect(
                jsonPath("$.rewards[1].['total_reward_EUR :']", is("1.00"))
        );
    }

当我运行测试时,我得到输出,

java.lang.AssertionError: No value at JSON path "$.rewards[0].['total_reward_EUR :']"

我调试并获取提供的值,

enter image description here

测试出了什么问题?

最佳答案

您应该像 $.rewards[0].['total_reward_EUR'] 一样使用它来访问 rewards 中第一个对象的 total_reward_EUR 属性> json 中的数组。

关于java.lang.AssertionError : No value at JSON path,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55687507/

相关文章:

java - 流中的叶子有什么作用?

java - 比较 DateTimes 的 JUnit 测试方法仅在从套件运行时失败

java - 在 Spring TestContext 中使用 DbUnit 的问题

java - 在andReturn中使用expect的方法参数

java - 在 Java 中给定 JSON 路径/JSON 指针获取 JSON 文件的行号

java - 如何启用/禁用 ToggleButton 的声音?

java - 实现通用解析器类

java - JSONPath 获取 JSON 字符串形式的数组元素

c# - 使用带有 JsonPath 的 SelectTokens 的问题/错误

java - m2eclipse 将 'target' 目录标记为 'Derived'