Mockmvn assertion 在 LocalDateTime & List 上失败



我试图断言一个REST响应,我正面临一些转换错误的时间来比较LocalDateTimeList<Scenario>。似乎JSON表示与正在使用的类型不匹配。

有人可以解释我(或指出我的文档,我可以从中提取)这个转换是如何工作的,请?

模型:

public class Control
{
private Long id;
private String name;
private LocalDateTime createdAt;
private Set<Scenario> scenarios = new HashSet<>();
// ...
}
public class Scenario
{
private Long id;
private String name;
}

响应主体:

{
"id":1,
"name":"Control-ABC"
"createdAt":"2021-05-31T10:11:12",       
"scenarios":[
{
"id":1,
"name":"Max"
},
{
"id":2,
"name":"Average"
}
]
}

断言:

mockMvc.perform(get("/control/find/" + control.getId()))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.id", equalTo(control.getId()), Long.class))
.andExpect(jsonPath("$.name", equalTo(control.getName())))
.andExpect(jsonPath("$.createdAt", is(control.getCreatedAt()), LocalDateTime.class))
.andExpect(jsonPath("$.scenarios", hasItems(control.getScenarios())));

论述:

java.lang.AssertionError: JSON path "$.createdAt"
Expected: is <2021-05-31T10:11:12>
but: was "2021-05-31T10:11:12"

java.lang.AssertionError: JSON path "$.scenarios"
Expected: (a collection containing <[Scenario(id=1, name=Max), Scenario(id=2, name=Average)]>)
but: a collection containing <[Scenario(id=1, name=Max), Scenario(id=2, name=Average)]> mismatches were: [was <{id=1, name=Max}>, was <{id=2, name=Average}>]

问题是您的测试线束不能在LocalDateTime和字符串之间转换类型。你需要为它做那个转换。

...
.andExpect(jsonPath("$.createdAt", control.getCreatedAt().toString()))
...

相关内容

最新更新