我正在测试SpringBoot控制器的get
方法,该方法提供以特定时间范围为基础编写的对象。
我意识到我可以在执行MockMvc之后获取json并使用对象映射器对其进行解析,使用一些流和一个断言,但是我想知道是否存在使用andExpect()序列进行构建的内置方法。
我尝试过Hamcrest日期匹配器,但是无法解析LocalDateTime格式
java.lang.AssertionError: JSON path "data.SENT[0].sentAt"
Expected: the date is within 10 days of "08 апр 2019 19:03:48 614ms +0300"
but: was "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"
} ],
我可以检查是否存在一些具体物体。但是我不能确定返回数据中没有该时段的记录。
答案 0 :(得分:0)
我做了一个自己的匹配器:
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)))