Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 to the JSP and the user is redirected to the proper URL. Here are the steps to do this:

  1. Add the spring-test and hamcrest-all Maven dependencies in pom.xml:

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId...