【问题标题】:how to pass date via url parameter - junit test with dates如何通过 url 参数传递日期 - 带日期的 junit 测试
【发布时间】:2018-04-28 19:43:48
【问题描述】:

我想通过参数传递我的日期,但我不知道该怎么做。我试过EncodeUrl.encode(),但没用(可能是我做错了什么)

@Test
public void getUsageCountersParam2Test() throws Exception {
    Date date = new Date(2017, 06, 23, 12, 39, 20);
    MvcResult result = mockMvc.perform(get(getUri("/usages?apiConsumerId=[1,2]&serviceId=1&dateFrom=" + date)).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andReturn();
    ObjectMapper mapper = new ObjectMapper();

    List<UsageCounterDetailsDto> list = mapper.readValue(result.getResponse().getContentAsString(), new TypeReference<List<UsageCounterDetailsDto>>() {
    });

    assertNotNull(list);
    assertEquals(3, list.size());
}

我有一个错误,例如:

org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam java.util.Date] for value 'Mon Jul 23 12:39:20 CEST 3917'; nested exception is java.lang.IllegalArgumentException

希望你能帮助我。

【问题讨论】:

  • This 可能会有所帮助。
  • 但在这种特殊情况下,您假设我应该修改控制器,而不仅仅是我想要的测试。目前数据库中的日期和时间戳应该相互调整。如果我没有得到更多答案,那么我会尝试这个(或者如果我的情况不正确)

标签: java junit controller url-parameters


【解决方案1】:

试试这样的:

    SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'Z", Locale.ENGLISH);
    String dateParam = sdf.format(date);
    MvcResult result = mockMvc.perform(get("/usages")
            .param("date", dateParam))
            .andExpect(status().isOk()).andReturn();

【讨论】:

    【解决方案2】:

    【讨论】:

      【解决方案3】:

      您可以使用@InitBinder 注解让控制器接受不同的日期格式。

      here is a one nice example

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-04
        • 2015-03-18
        • 2014-05-02
        • 2023-01-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多