Unit testing the logic of controller methods is usually difficult, but Spring makes it easy by providing methods to simulate a request and test the response generated by Spring.
We'll test this controller method which concatenates two parameters and passes the result to the concat.jsp
JSP file:
@RequestMapping("concat") public String concat(@RequestParam String a, @RequestParam String b, Model model) { String result = a + b; model.addAttribute("result", result); return "concat"; }
To test a controller method, build and execute an HTTP request and then perform tests on the response returned by the controller method. We will test that for a given set of parameters, the correct attribute is passed to the JSP and the user is redirected to the proper URL. Here are the steps to do this:
Add the
spring-test
andhamcrest-all
Maven dependencies inpom.xml
:<dependency> <groupId>org.springframework</groupId> <artifactId...