Book Image

Mockito for Spring

By : Sujoy Acharya
Book Image

Mockito for Spring

By: Sujoy Acharya

Overview of this book

Table of Contents (12 chapters)
Mockito for Spring
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Mocking the servlet container with MockMvc


The design behind the Spring MVC test is to test the controller by performing actual requests and generating responses, as they would be at runtime. MockMvc is used to mock the servlet container, and it can perform a request and verify the resulting response status and response elements. We'll build a Spring controller to generate a JSON response as in the case of a rest controller and then use MockMvc to unit test the request and the response:

  1. Create a serializable Employee POJO class that holds employee information, such as ID, name, and salary.

  2. Create a controller to return a specific employee and all employees with /employees/{id} and /employees/ urls. We'll create a HashMap and store dummy employees. The following is the class:

    @Controller
    public class HRController {
      private Map<Integer, Employee> database = new HashMap<Integer, 
            Employee>();
      public HRController() {
        loadDummyData();
      }
      private void loadDummyData...