问题
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.
回答1:
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();
回答2:
I had this same issue and found that adding the @DateTimeFormat annotation to my controller helped.
Helpful Links: How to accept Date params in a GET request to Spring MVC Controller?
Spring MVC controller with date
https://codingexplained.com/coding/java/spring-framework/date-parameter-in-spring-mvc-controller
回答3:
You can use @InitBinder annotation to allow controller to accept different date formats.
here is a one nice example
来源:https://stackoverflow.com/questions/47309847/how-to-pass-date-via-url-parameter-junit-test-with-dates