-1

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.

xross
  • 597
  • 4
  • 9
  • 25
  • 2
    [This](https://stackoverflow.com/questions/15164864/how-to-accept-date-params-in-a-get-request-to-spring-mvc-controller) might help. – Andrew S Nov 15 '17 at 14:28
  • But in that particular case you are assuming that I should modify controller not only test as I primaly want. At the moment Date and Timestamp from DB should be adjusted to each other. If I wouldnt gain any more answers then I will try this one (or if my case turn out to be incorrect) – xross Nov 15 '17 at 14:36

3 Answers3

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();
sergey
  • 368
  • 2
  • 7
0

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

CodeNameGrant
  • 124
  • 4
  • 16
0

You can use @InitBinder annotation to allow controller to accept different date formats.

here is a one nice example

Jovo Skorupan
  • 237
  • 2
  • 5