Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

java - how to pass date via url parameter - junit test with dates

I want to pass my Date via parameter, and I dont exactly know how to do it. I have tried EncodeUrl.encode(), but it didnt work (it is possible that I did something wrong)

@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());
}

I have an error such as:

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

Hope you could helped me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try something like this:

    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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...