是否有任何适当的匹配器来解析和比较MockMvc的Json响应中的LocalDateTime字段

问题描述 投票:0回答:1

我正在测试我的SpringBoot控制器的get方法,它提供了在特定时间范围内编写的对象。

我意识到我可以在mockMvc执行后获取json并使用对象映射器解析它,使用一些流和一个断言,但我想知道是否有内置的方法来使用andExpect()序列。

我已经尝试过Hamcrest Date Matchers,但它无法解析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"
    } ],

我可以检查是否有一些具体的对象。但我不能确定我的返回数据中没有时间段记录。

java testing jsonpath matcher mockmvc
1个回答
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)))
© www.soinside.com 2019 - 2024. All rights reserved.