使用Spring MockMVC

时间:2017-10-09 14:51:40

标签: json spring spring-mvc mockmvc

我正在尝试在Spring MVC Web服务返回的JSON结果中验证LocalDate对象,但我无法弄清楚如何。

目前我总是遇到断言错误,如下所示:

  

java.lang.AssertionError:JSON路径“$ [0] .startDate”预期:是   < 2017年1月1日与GT;        但是:是< [2017,1,1]>

我的测试的重要部分发布在下面。任何想法如何修复测试通过?

import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;

public class WebserviceTest {

    @Mock
    private Service service;

    @InjectMocks
    private Webservice webservice;

    private MockMvc mockMvc;

    @Before
    public void before() {
        mockMvc = standaloneSetup(webservice).build();
    }

    @Test
    public void testLocalDate() throws Exception {
        // prepare service mock to return a valid result (left out)

        mockMvc.perform(get("/data/2017")).andExpect(status().isOk())
            .andExpect(jsonPath("$[0].startDate", is(LocalDate.of(2017, 1, 1))));
    }
}

webservice返回一个视图对象列表,如下所示:

public class ViewObject {

    @JsonProperty
    private LocalDate startDate;
}

[编辑]

另一次尝试是

.andExpect(jsonPath("$[0].startDate", is(new int[] { 2017, 1, 1 })))

导致

  

java.lang.AssertionError:JSON路径“$ [0] .startDate”预期:是   [< 2017>,< 1>,< 1>]        但是:是< [2017,1,1]>

[编辑2] 返回的startDate对象似乎是类型:net.minidev.json.JSONArray

4 个答案:

答案 0 :(得分:1)

JSON响应中的LocalDate将类似于“startDate”:

"startDate": {
    "year": 2017,
    "month": "JANUARY",
    "dayOfMonth": 1,
    "dayOfWeek": "SUNDAY",
    "era": "CE",
    "dayOfYear": 1,
    "leapYear": false,
    "monthValue": 1,
    "chronology": {
        "id": "ISO",
        "calendarType": "iso8601"
    }
}

所以,你应该检查下面的每个属性:

.andExpect(jsonPath("$[0].startDate.year", is(2017)))
                .andExpect(jsonPath("$[0].startDate.dayOfMonth", is(1)))
                .andExpect(jsonPath("$[0].startDate.dayOfYear", is(1)))

答案 1 :(得分:0)

我认为在那个级别你正在验证Json而不是解析对象。所以你有一个字符串,而不是LocalDate。

所以基本上尝试更改代码:

...
.andExpect(jsonPath("$[0].startDate", is("2017-01-01"))));

答案 2 :(得分:0)

这是要走的路。感谢'Amit K Bist'指出我正确的方向

...
.andExpect(jsonPath("$[0].startDate[0]", is(2017)))
.andExpect(jsonPath("$[0].startDate[1]", is(1)))
.andExpect(jsonPath("$[0].startDate[2]", is(1)))

答案 3 :(得分:0)

这应该通过:

.andExpect(jsonPath("$[0].startDate", is(LocalDate.of(2017, 1, 1).toString())));
相关问题