How to Test Your Spring MVC Controller
by , 11-27-2011 at 10:21 PM (2432 Views)
In my previous post, I showed you how to create a HomeController for our home page in your application. You might have noted that there was little code that linked your HomeController with Spring that was included. It is simply a plain old java object (POJO). In this tip, we will look at unit testing your controller. Unit testing your controller will be very easy since a POJO doesn’t need you to mock any Spring or other specific objects. I will create a test object using standard naming conventions, XXXTest, in order to do this. In the case of our home controller, it will be HomeControllerTest.
First note that I have used Google’s open source Mockito mock framework in order to provide a mock implementation of CarService. With the mock CarService I just create a new instance of HomeController and then call the showHomePage() method. I then assert the car list returned from the mock CarService in the model Map under the cars key. This method returns a logical view name of home.Java Code:import static com.acme.springwebapp.web.HomeController.*; import static java.util.Arrays.*; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import java.util.HashMap; import java.util.List; import org.testng.annotations.Test; import com.acme.springwebapp.domain.Car; import com.acme.springwebapp.service.CarService; public class HomeControllerTest { @Test public void shouldDisplayRecentCars() { List<Car> expectedCars = asList(new Car(), new Car(), new Car()); CarService carService = mock(CarService.class); when(carService.getCars(DEFAULT_CARS_PER_PAGE)) .thenReturn(expectedCars); HomeController controller = new HomeController(carService); HashMap<String, Object> model = new HashMap<String, Object>(); String viewName = controller.showHomePage(model); assertEquals("home", viewName); assertSame(expectedCars, model.get("cars")); verify(carService).getCars(DEFAULT_CARS_PER_PAGE); } }









Email Blog Entry
License4J 4.0
Yesterday, 12:23 AM in Java Software