Unit testing controller methods

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.

Getting ready

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";
}

How to do it…

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 ...

Get Spring Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.