我只能使用MockHttpServletRequestBuilder进行测试,而我只是将字符串作为参数发布。
如何将日期作为参数发布,因为我的下面的FormattingConversionService似乎无法用于jUnit测试,而我的spring基础架构没有将String值转换为Calendar值。
@Bean
public FormattingConversionService mvcConversionService() {
DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService();
DateFormatterRegistrar formatterRegistrar = new DateFormatterRegistrar();
formatterRegistrar.setFormatter(new DateFormatter("yyyy-MM-dd"));
formatterRegistrar.registerFormatters(conversionService);
return conversionService;
}
我试图做的测试是:
@Test @Transactional
public void shouldSaveABill() throws Exception {
String dueDate = "05/25/2017";
MockHttpServletRequestBuilder request = MockMvcRequestBuilders
.post("/saveBill")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("id", "1")
.param("description", "Food")
.param("dueDate", "05/25/2017")
.param("value", "150");
mockMvc.perform(request)
.andExpect(MockMvcResultMatchers.status().is(302))
.andExpect(MockMvcResultMatchers.forwardedUrl("/someUrl"));
}
在调试测试时,我收到错误:
Field error in object 'bill' on field 'dueDate': rejected value [05/25/2017]; codes [typeMismatch.bill.dueDate,typeMismatch.dueDate,typeMismatch.java.util.Calendar,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [bill.dueDate,dueDate]; arguments []; default message [dueDate]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Calendar' for property 'dueDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Calendar] for value '05/25/2017'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [05/25/2017]]
请问,使用jUnit,spring和MockHttpServletRequestBuilder测试具有Calendar类型字段的实体的持久性的最佳方法是什么?还有另一种方法可以实现这一目标吗?我感谢任何帮助。感谢。