Issues testing my Spring MVC Controllers - java

I have the following controller method. A user submits a search form with 4 input fields and has to fill in at least one of the field. If all the fields are empty (using the validator) then an error will be displayed on top of the form (in the same page).
Otherwise it will use the service method to look for users and display the results at the bottom of the form (in the same page). That is why in the if statement I return the same page as well as the end of the method because whatever happens the user is directed to the same page
#RequestMapping(value="/search", method={RequestMethod.POST})
public ModelAndView searchUser(#ModelAttribute("searchUserDTO")SearchUserDTO searchUserDTO, BindingResult bindingResult, ModelMap modelMap){
validate(searchUserDTO, bindingResult);
List<BlueUser> users = new ArrayList<>();
if (bindingResult.hasErrors()) {
modelMap.put("searchUserDTO", searchUserDTO);
return new ModelAndView(VIEW_USERS, modelMap);
} else {
users = BlueUserService.findUsers(searchUserDTO.getMyName, searchUserDTO.getSSID(), searchUserDTO.getPostcode(), new Email(searchUserDTO.getMail()));
}
modelMap.put("searchUserDTO", users);
return new ModelAndView(VIEW_USERS, modelMap);
}
validator method
#Override
public void validate(Object target, Errors errors) {
SearchUserDTO dto = (SearchUserDTO)target;
if(dto.getMyName()==null && dto.getSSID() == null && dto.getPostcode() == null && dto.getMail()==null){
errors.reject(EMPTY, "Please fill in the form");
}
}
I use reject to return error in the global scope and not on specific field and the following test method:
public static final String BINDING_RESULT = BindingResult.class.getName() + '.' + "searchUserDTO";
#Test
public void searchUserPOST() throws Exception{
MultiValueMap<String, String> paramMap = mockMVCTestUtil.createParamMap("myName", null,
"ssid", null,
"postcode", null,
"mail", null);
MvcResult mvcResult = this.mockMvc.perform(
post("/search")
.params(paramMap))
.andExpect(model().attributeExists("searchUserDTO"))
.andExpect(model().attributeHasErrors("searchUserDTO"))
.andExpect(status().isOk())
.andExpect(redirectedUrl(VIEW_USERS))
.andExpect(forwardedUrl(VIEW_USERS))
.andReturn();
BindingResult bindingResult = (BindingResult) mvcResult.getModelAndView().getModel().get(BINDING_RESULT);
assertNotNull(bindingResult);
assertGlobalErrorMessage(bindingResult, "Please fill in the form");
}
When I run the test method it fails and i get the following error messages:
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: No errors for attribute 'searchUserDTO'
What am I doing wrong?

Related

Redirect ModelAndView with message

My application has a method to update a conference. After doing so I have a modelandview with a redirect to the main conference list. This all works fine although the message which I add as an object to the modelandview does not display.
My method in my controller:
#PostMapping("/updateConference")
public ModelAndView updateConference(
#ModelAttribute("conference") #Valid ConferenceDto conferenceDto, BindingResult result) {
if(result.hasErrors()){
return new ModelAndView("updateConference","conferenceDto", conferenceDto);
}
try {
conferenceService.updateConference(conferenceDto);
} catch (ConferenceAlreadyExistException uaeEx) {
ModelAndView mav = new ModelAndView("updateConference","conferenceDto", conferenceDto);
mav.addObject("message", uaeEx.getMessage());
return mav;
}
ModelAndView mav = new ModelAndView("redirect:/teacher/configure"); // Problem is here
mav.addObject("message", "Successfully modified conference.");
return mav;
}
In my html I have the line:
<div th:if="${message != null}" th:align="center" class="alert alert-info" th:utext="${message}">message</div>
After updating the conference it goes back to configure.html although the message does not show. In the url I can see http://localhost:8080/teacher/configure?message=Successfully+modified+conference
I have looked at this thread although it did not help.
I tried to experiment by setting ModelAndView mav = new ModelAndView("configure") and the message displays but my conference list is empty and the url is http://localhost:8080/teacher/updateconference
Any tips is highly appreciated!
EDIT
I have tried to use RedirectAttributes as crizzis pointed out & this page and have this now:
#PostMapping("/updateConference")
public String updateConference(
#ModelAttribute("conference") #Valid ConferenceDto conferenceDto, BindingResult result, RedirectAttributes attributes) {
if(result.hasErrors()){
attributes.addFlashAttribute("org.springframework.validation.BindingResult.conferenceDto", result);
attributes.addFlashAttribute("conferenceDto", conferenceDto);
return "redirect:/teacher/updateConference";
}
try {
conferenceService.updateConference(conferenceDto);
} catch (ConferenceAlreadyExistException uaeEx) {
attributes.addFlashAttribute("conferenceDto", conferenceDto);
attributes.addFlashAttribute("message", uaeEx.getMessage());
return "redirect:/teacher/updateConference";
}
attributes.addFlashAttribute("message", "Successfully modified conference.");
return "redirect:/teacher/configure";
}
My get method:
#GetMapping(path = "/updateConference/{id}")
public String showUpdateConferenceForm(#PathVariable(name = "id") Long id, Model model){
Optional<Conference> conference = conferenceService.findById(id);
if (!model.containsAttribute("ConferenceDto")) {
model.addAttribute("conference", new ConferenceDto());
}
return "updateConference";
}
This works as intended and my message is shown on my configure.html . However, when I have an error in BindingResults the application goes to an error page and I get this in the console:
Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported]
Use RedirectAttributes which has addFlashAttribute method. You can set the success or failure message like you did and access that message through the key in the redirected page as you need.
when the error occurs you are redirecting to the same method instead of this you can just render the template in case there is error. I do this way.

Mock BindingResult in unit test case when user does not exist

I'm very new to Mockito and Junit. I'm working on creating test case for forgot password workflow. Below is the code for controller and test. Could anyone tell me how should I test on bindingresult?
#RequestMapping(value = "/user/public/forgotPassword", method = RequestMethod.POST)
public ModelAndView sendforgetPasswordLink(#ModelAttribute ForgetPasswordBean forgetPasswordBean,BindingResult result, HttpSession session) {
BreadCrumbBuilder.addLinktoBreadCrumb(session, new Link(Constants.FORGET_PASSWORD_TITLE, "/user/public/forgotPassword", Constants.GROUP_USER, 0));
Map<String, String> breadCrumbs = HomePageController.setupInitialBreadCrumbs(session);
breadCrumbs.put(Constants.FORGET_PASSWORD_TITLE, "/user/public/forgotPassword");
session.setAttribute(SessionAttributes.BREAD_CRUMBS,breadCrumbs);
ModelAndView mav = new ModelAndView();
mav.addObject("displayTitle", Constants.FORGET_PASSWORD_TITLE);
PublicUser user = publicUserService.findPublicUserByEmail(forgetPasswordBean.getEmail().toLowerCase());
if(user == null) {
result.reject("email", "An account does not exist for this email.");
mav.setViewName("publicuser/forgetPassword.jsp");
return mav;
}
String randomId = java.util.UUID.randomUUID().toString();
user.setTempId(randomId);
mailService.sendForgetPasswordLink(user);
publicUserService.savePublicUser(user);
String msg = "Password reset instructions have been sent to your email.";
mav.addObject("msg", msg);
mav.setViewName("message.jsp");
return mav;
}
This is test I created so far
#Test
public void TestForgetPasswordForNoUserFound() throws Exception {
final String input_email = "abc#test.com";
ForgetPasswordBean forgetPasswordBean = new ForgetPasswordBean();
forgetPasswordBean.setEmail(input_email);
PublicUser daoUser = new PublicUser();
daoUser.setEmail(input_email);
when(mockPublicUserService.findPublicUserByEmail(input_email)).thenReturn(null);
when(mockBindingResult.hasErrors()).thenReturn(true);
final ModelAndView modelAndView = controller.sendforgetPasswordLink(forgetPasswordBean, mockBindingResult, mockHttpSession);
ModelMap modelMap = modelAndView.getModelMap();
assertEquals("An account does not exist for this email.", modelMap.get(mockBindingResult));
assertEquals("publicuser/forgetPassword.jsp", modelAndView.getViewName());
assertModelAttributeValue(modelAndView, "displayTitle", Constants.FORGET_PASSWORD_TITLE);
}
What you can do is verify behavior of your BindingResult by checking that the reject method was called.
Basically instead of
assertEquals("An account does not exist for this email.", modelMap.get(mockBindingResult));
You can do the following
Mockito.verify(mockBindingResult).reject("email", "An account does not exist for this email.");
And that way you can verify that the method was called.

spring mvc #ExceptionHandler method get same view

My problem is that I want to create an #ExceptionHandler method that will capture all un-handled exceptions. Once captured I would like to redirect to the current page instead of specifying a separate page just to display error.
Basically how do I get the value of someview returned by somemethod and set it dynamically in the method unhandledExceptionHandler below.
#ExceptionHandler(Exception.class)
protected ModelAndView unhandledExceptionHandler(Exception ex){
System.out.println("unhandle exception here!!!");
ModelAndView mv = new ModelAndView();
mv.setViewName("currentview");
mv.addObject("UNHANDLED_ERROR", "UNHANDLED ERROR. PLEASE CONTACT SUPPORT. "+ex.getMessage());
return mv;
}
#RequestMapping(value = "/somepage", method = RequestMethod.GET)
public String somemethod(HttpSession session) throws Exception {
String abc = null;
abc.length();
return "someview";
}
So in JSP I can render this error message back into the current page something like that.
<c:if test="${not empty UNHANDLED_ERROR}">
<div class="messageError"> ${UNHANDLED_ERROR}</div>
</c:if>
I don't think there is way to do what you are asking for, because in the exception handler method unhandledExceptionHandler there is no way to find out what the name of the view that the handler method somemethod would have returned.
The only way is for you to introduce some sort of meta data scheme so that when you end up in the exception handler you can figure out what view to map it to. But I think this meta data scheme would be fairly complex. You can implement such a scheme by finding out what was the original url being accessed when the exception was thrown, this can be done with the code snippet below.
(ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest()
Once you know what the original request URL you can redirect to it, maybe using flash attribute to store the fact that there was an exception and what the error is.
The main problem wit the metadata will occur when you have a handler method that select between different views something like.
#RequestMapping(value = "/somepage", method = RequestMethod.GET)
public String somemethod(HttpSession session) throws Exception {
String abc = null;
if(someCondition) {
abc.length();
return "someview";
} else {
// do some stuff here.
return "someOtherView";
}
}
Even knowing that somemethod was the source of the error leaves you not knowing which branch in the if statement caused the exception.
I dont think you can do this without modifying all of your handler methods. However you can try to do this in a "pretty" way:
1) You can define your own annotation which will accept target view name as a parameter (e.g. #ExceptionView)
2) Next thing to do is marking your handler methods with it, e.g.:
#ExceptionView("someview")
#RequestMapping(value = "/somepage", method = RequestMethod.GET)
public String somemethod(HttpSession session) throws Exception {
String abc = null;
abc.length();
return "someview";
}
3) After that you can do something like this in exception handler:
#ExceptionHandler(Exception.class)
protected ModelAndView unhandledExceptionHandler(Exception ex, HandlerMethod hm) {
String targetView;
if (hm != null && hm.hasMethodAnnotation(ExceptionView.class)) {
targetView = hm.getMethodAnnotation(ExceptionView.class).getValue();
} else {
targetView = "someRedirectView"; // kind of a fallback
}
ModelAndView mv = new ModelAndView();
mv.setViewName(targetView);
mv.addObject("UNHANDLED_ERROR", "UNHANDLED ERROR. PLEASE CONTACT SUPPORT. "+ex.getMessage());
return mv;
}
Rather than sending the error on a separate page, you can you just put the error in the ModelAndView object. In your case you can just put the try/catch in your controller method and return the same view like so:
#RequestMapping(value = "/somepage", method = RequestMethod.GET)
public String somemethod(ModelAndView mv,HttpSession session) throws Exception {
mv.setViewName("someview");
try{
String abc = null;
abc.length();
} catch(Exception e) {
mv.addObject("UNHANDLED_ERROR", "UNHANDLED ERROR. PLEASE CONTACT SUPPORT. "+ex.getMessage());
}
return mv;
}
So add the ModelAndView to your method and return it.
I have not tried this out, but based on the documentation here, we can get the request object in the exception handler. We may not be able to get the view linked to the URL. Getting the view from the URL, and the state/model of the view will be the tricky part.
#ExceptionHandler(Exception.class)
public ModelAndView handleError(HttpServletRequest req, Exception ex) {
logger.error("Request: " + req.getRequestURL() + " raised " + ex);
ModelAndView mav = new ModelAndView();
mav.addObject("exception", ex);
mav.addObject("url", req.getRequestURL());
mav.setViewName("error");
return mav;
}
Create a controller method annotated with #RequestMethod("/server-error")
Create a controller method annotated with #ExceptionHandler which will return "forward:/server-error";

How to pass errors in Spring Controller/Model to a view file

How do I pass errors to a view file from a Controller implemented using Spring MVC? These errors are not form errors. Just business logic errors that will be shown inside a div in the "JSP" view.
Here is the controller action I have:
#RequestMapping(method = RequestMethod.POST)
public String processLoginForm(HttpServletRequest request, LoginForm loginForm,
BindingResult result, #SuppressWarnings("rawtypes") Map model)
{
loginForm = (LoginForm) model.get("loginForm");
String gotoURL = request.getParameter("gotoURL");
if (gotoURL == null || gotoURL == "")
{
String errorMessage = "No Redirect URL Specified";
return "loginerror";//loginerror is the view file I want to pass my error to.
}
model.put("loginForm", loginForm);
return "loginsuccess";
}
Thanks,
Change your method signature :
public String processLoginForm(HttpServletRequest request, LoginForm loginForm,
BindingResult result, ModelMap model)
You can put the error message in the ModelMap and forward it to the loginerror page.
if (gotoURL == null || "".equals(gotoURL))
{
final String errorMessage = "No Redirect URL Specified";
modelMap.addAttribute("errorMessage ", errorMessage);
return "loginerror";//loginerror is the view file I want to pass my error to.
}
You can fetch that in the div using EL.
<div>${errorMessage}</div>
Your method is
public String processLoginForm(HttpServletRequest request, LoginForm
loginForm, BindingResult result, #SuppressWarnings("rawtypes") Map
model)
The method #The New Idiot explained is
public String processLoginForm(HttpServletRequest request, LoginForm
loginForm,
BindingResult result, ModelMap model)
See that the Map model is replaced with ModelMap model
If you use this method, then you can use model.addAttribute to add error messages
You can use Spring support for exception handling..
HandlerExceptionResolver or #ExceptionHandler
#adarshr
Link
Hope it will be of some use.

SpringMVC parameter issue in url

I have a page which i enter parameters to query a list of records.
When the query button is clicked i get the list when an item form the list is clicked it takes me back to the first page with the record in display.
When i hit another button 'new' to clear the page and return an empty page a parameter is there in the url and it sets the value of an item on the page.The item that is there in the url is the crimeRecNo.
How can i get rid of this i want to return an empty page?
Scenario
I am on a page with the following url :http://adomain/crimeTrack/crime_registration.htm
I click Query which does a POST to another url which displays the list of records :http://adomain/crimeTrack/crimeList.htm
On the above page in 2 above i then select one record which does a POST and takes me to the followig url: http://adomain/crimeTrack/getCrime/6.htm - where 6 is the crimeRecNo.
I am now on the above url and i hit the 'NEW' button to get a blank form with the url in 1 above. When i hit new a POST is done to the controller method in code sample 4 under
This method does a redirect to the url which is mapped to a GET method however the final url looks like this : http://adomain/crimeTrack/%20crime_registration.htm?crimeRecNo=6
The value 6 remains in the crimeRecNo field and the entire form is not cleared.
Under is the controller methods:
1. Initial page request
#RequestMapping(value = "crime_registration.htm", method = RequestMethod.GET)
public ModelAndView loadPage(HttpServletRequest request,HttpServletResponse response, #ModelAttribute Crime crime,BindingResult result, ModelMap m, Model model, SessionStatus status,HttpSession session) throws Exception {
try {
logger.debug("In Crime Registration Controller");
myCriminalList.put("dbcriminalList",
this.citizenManager.getListOfCriminals());
...................
session.setAttribute("page", 0);
return new ModelAndView("crime_registration");
} catch (Exception e) {
logger.debug("Exception In CrimeRegistration Controller : "
+ e.getMessage());
return new ModelAndView("crime_registration");
}
}
2. Query For List of Items
#RequestMapping(value = "crimeList.htm", method = RequestMethod.POST)
public ModelAndView handelCrimeList(#ModelAttribute Crime crime,
BindingResult result, ModelMap m, Model model) throws Exception {
if (crimeManager.getCrimesList(crime).size() <= 0) {
model.addAttribute("dbcriminals", myCriminalList);
........
model.addAttribute("crimeTypeList", crimeTypeManager.getCrimeTypeList(crime.getOffenceCatId()));
model.addAttribute("icon", "ui-icon ui-icon-circle-close");
model.addAttribute("results","Error: Query Caused No Records To Be Retrieved!");
return new ModelAndView("crime_registration");
}
model.addAttribute("crimes", crimeManager.getCrimesList(crime));
return new ModelAndView("crimeList");
}
3. Request For One Item/When item is selected from list
#RequestMapping(value = "getCrime/{crimeRecNo}.htm", method = RequestMethod.POST)
public ModelAndView getCrime(#PathVariable Integer crimeRecNo,
#ModelAttribute Crime crime, BindingResult result, ModelMap m,
Model model, HttpServletRequest request,
HttpServletResponse response, HttpSession session) throws Exception {
try {
model.addAttribute("crime", crimeManager.getCrimeRecord(crimeRecNo));
session.setAttribute("crimeRecNo", crimeRecNo);
//model.addAttribute("victimList", citizenManager.getVictimListByCrimeRecNo(crimeRecNo));
} catch (Exception e) {
logger.error("Exception in CitizenRegistrationController - ModelAndView getCitizen "
+ e);
}
int crimeCatId = crimeManager.getCrimeRecord(crimeRecNo).getOffenceCatId();
logger.info("crime category number is : "+crimeCatId);
myCrimeTypeList.put("crimeTypeList", this.crimeTypeManager.getCrimeTypeList(crimeCatId));
model.addAttribute("dbcriminals", myCriminalList);
.....
session.setAttribute("crimeRecNo", crimeRecNo);
return new ModelAndView("crime_registration");
}
4. Request For NEW Form
#RequestMapping(value = "crime_registration_new.htm", method = RequestMethod.POST)
public String loadNew(HttpServletRequest request,Model model,
HttpServletResponse response,SessionStatus status,HttpSession session) throws Exception {
status.setComplete();
return "redirect: crime_registration.htm";
//return new ModelAndView(new RedirectView("crime_registration.htm"));
}
Adding this to 4 did the trick
#RequestMapping(value = "crime_registration_new.htm", method = RequestMethod.POST)
public String loadNew(HttpServletRequest request,Model model,
HttpServletResponse response,SessionStatus status,HttpSession session) throws Exception {
status.setComplete();
model.addAttribute("crime", new Crime());
return "redirect: crime_registration.htm";
//return new ModelAndView(new RedirectView("crime_registration.htm"));
}

Categories