我正在测试我的 SpringBoot Controller 的 get
方法,它提供在特定时间范围内以 base 编写的对象。
我意识到我可以在 mockMvc 执行后获取 json 并使用对象映射器解析它,使用一些流和一个断言,但我想知道是否有内置的方法来使用 andExpect() 序列。
我试过 Hamcrest Date Matchers,但它无法解析 LocalDateTime 格式
java.lang.AssertionError: JSON 路径“data.SENT[0].sentAt”
预期:日期在“08 апр 2019 19:03:48 614ms +0300”的 10 天内
但是:是“2019-04-02T11:36:16.51”
this.mockMvc.perform(get(BASE_URL)
.accept(MediaType.APPLICATION_JSON_VALUE)
.contentType(MediaType.APPLICATION_JSON)
.content(jsonMockObjectMapper.writeValueAsString(smsStatisticFullRequest)))
.andExpect(status().isOk())
.andExpect(jsonPath("data.SENT[*].sentAt", Matchers.hasItems("2019-04-02T11:36:16.51")))
// .andExpect(jsonPath("data.SENT[0].sentAt", DateMatchers.within(10, TimeUnit.DAYS, Timestamp.valueOf(LocalDateTime.now()))))
// .andExpect(jsonPath("data.SENT[0].sentAt", DateMatchers.before(Timestamp.valueOf(LocalDateTime.now()))))
.andDo(CustomResultHandler.handleResult(name.getMethodName(), MockMvcRestDocumentation::document));
我期望能够检查返回数据中的所有对象是否在断言时间范围内。
Content-Type: application/json;charset=UTF-8
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
{
"apiVersion" : "1.0.1",
"error" : false,
"data" : {
"SENT" : [ {
"id" : 3,
"phone" : "9111233456",
"userId" : 683581,
"sentAt" : "2019-04-02T11:36:16.51",
"operation" : "RECOVERY_PASSWORD",
"smsCode" : "2112"
} ],
我可以检查是否有一些具体的对象。但是我不能确定我的回程数据中没有任何时间段的记录。
最佳答案
我已经制作了自己的匹配器:
import net.minidev.json.JSONArray;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import java.time.LocalDateTime;
class CustomMatcher extends BaseMatcher<LocalDateTime> {
private LocalDateTime from;
private LocalDateTime to;
private int misMatchAtIndex;
CustomMatcher(LocalDateTime from, LocalDateTime to) {
this.from = from;
this.to = to;
}
@Override
public boolean matches(Object item) {
JSONArray rawData = (JSONArray) item;
for (Object raw : rawData) {
LocalDateTime parsed = LocalDateTime.parse(raw.toString());
if (!parsed.isBefore(to) || !parsed.isAfter(from)) {
misMatchAtIndex = rawData.indexOf(raw);
return false;
}
}
return true;
}
@Override
public void describeTo(Description description) {
description.appendText(String.format("All DateTime fields from %s to %s, mismatch at index %d",
from, to, misMatchAtIndex));
}
}
使用:
.andExpect(jsonPath("data." + SENT + "[*].sentAt", new CustomMatcher(fromDate, toDate)))
关于java - 是否有任何合适的匹配器来解析和比较来自 MockMvc 的 Json 响应中的 LocalDateTime 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55577724/