Hi Rossen, I've got a similar issue.
So, my test:
Code:
public void saveChosenPaymentTypeTest2() throws Exception {
//no payment type selected
mockMvc.perform(post("/order/savePayment"))
.andDo(print())
.andExpect(model().attributeHasErrors("paymentType"))
.andExpect(model().errorCount(1))
.andExpect(status().isOk())
.andExpect(forwardedUrl("order.select.paymentType"));
}
Controller method:
Code:
@RequestMapping(value = "/savePayment", method = RequestMethod.POST)
public ModelAndView saveChosenPaymentType(@Valid SavePaymentTypeForm form, BindingResult bindingResult ,
HttpSession session) {
if (bindingResult.hasErrors()) {
ModelAndView mav = new ModelAndView("order.select.paymentType");
mav.addObject(bindingResult.getTarget());
return mav;
}
ModelAndView mav = new ModelAndView("redirect:/order/confirmation");
session.setAttribute(ORDER_PAYMENT_TYPE_SESSION_KEY, form.getPaymentType());
return mav;
}
The class that should be validated
Code:
public class SavePaymentTypeForm {
@NotNull(message = "{order.savePayment.error.paymentType.not.selected}")
private PaymentType paymentType;
public PaymentType getPaymentType() {
return paymentType;
}
public void setPaymentType(PaymentType paymentType) {
this.paymentType = paymentType;
}
}
and results of .andDo(print())
Code:
MockHttpServletRequest:
HTTP Method = POST
Request URI = /order/savePayment
Parameters = {}
Headers = {}
Handler:
Type = com.euroit.militaryshop.web.controller.OrderWizardController
Method = public org.springframework.web.servlet.ModelAndView com.euroit.militaryshop.web.controller.OrderWizardController.saveChosenPaymentType(com.euroit.militaryshop.web.form.SavePaymentTypeForm,org.springframework.validation.BindingResult,javax.servlet.http.HttpSession)
Resolved Exception:
Type = null
ModelAndView:
View name = order.select.paymentType
View = null
Attribute = trolley
value = Mock for TrolleyImpl, hashCode: 1397618175
errors = []
Attribute = savePaymentTypeForm
value = com.euroit.militaryshop.web.form.SavePaymentTypeForm@75044c61
errors = [Field error in object 'savePaymentTypeForm' on field 'paymentType': rejected value [null]; codes [NotNull.savePaymentTypeForm.paymentType,NotNull.paymentType,NotNull.com.euroit.militaryshop.enums.order.PaymentType,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [savePaymentTypeForm.paymentType,paymentType]; arguments []; default message [paymentType]]; default message [{order.savePayment.error.paymentType.not.selected}]]
FlashMap:
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = order.select.paymentType
Redirected URL = null
Cookies = []
And the test fails with message "No BindingResult for attribute: paymentType
". Where can be the problem?