JsonPathResultMatchers无法成功验证响应

时间:2018-08-27 11:51:20

标签: java junit integration-testing

为什么JsonPathResultMatchers无法成功验证响应? 测试

private static final UUID TRANSACTION_UUID_ONE = UUID.fromString("336ca9de-1583-4f39-9c67-f8380323d09d");

restBalanceMockMvc.perform(put("/api/balance")
        .contentType(TestUtil.APPLICATION_JSON_UTF8)
        .content(TestUtil.convertObjectToJsonBytes(transaction)))
        .andExpect(status().isOk())
        .andExpect(jsonPath("$.transactionId").value(hasItem(TRANSACTION_UUID_ONE.toString())))
        .andExpect(jsonPath("$.errorCode").value(hasItem("")))
        .andExpect(jsonPath("$.balanceVersion").value(hasItem(UPDATED_BALANCE_VERSION)))
        .andExpect(jsonPath("$.balanceChange").value(hasItem(BALANCE_CHANGE)))
        .andExpect(jsonPath("$.balanceAfterChange").value(hasItem(BALANCE_AFTER_CHANGE)));

回复:

{"username":"player1","transactionId":"336ca9de-1583-4f39-9c67-f8380323d09d","balanceChange":2,"errorCode":"","balanceVersion":1,"balanceAfterChange":5.00}

错误

java.lang.AssertionError: JSON path "$.transactionId"
Expected: a collection containing "336ca9de-1583-4f39-9c67-f8380323d09d"
     but: was "336ca9de-1583-4f39-9c67-f8380323d09d"
Expected :a collection containing "336ca9de-1583-4f39-9c67-f8380323d09d"

Actual   :"336ca9de-1583-4f39-9c67-f8380323d09d"

1 个答案:

答案 0 :(得分:0)

JsonPathResultMatchers.value()期望Hamcrest Matcher会评估该值。

hasItem()的定义如下:

  

Iterables创建一个匹配器,该匹配器仅在经过检查的Iterables的单次通过产生至少一个等于指定的item的项目时才匹配。

JSON中的

transactionId是常规字符串而不是集合,因此此处不能使用hasItem()

尝试

jsonPath("$.transactionId").value(equalTo(TRANSACTION_UUID_ONE.toString()))

或者只是

jsonPath("$.transactionId").value(TRANSACTION_UUID_ONE.toString())