View RSS Feed

Spring Framework

How to Test Your Spring MVC Controller

Rate this Entry
by , 11-27-2011 at 10:21 PM (3837 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.

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);
	}
}
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.

Submit "How to Test Your Spring MVC Controller" to Facebook Submit "How to Test Your Spring MVC Controller" to Digg Submit "How to Test Your Spring MVC Controller" to del.icio.us Submit "How to Test Your Spring MVC Controller" to StumbleUpon Submit "How to Test Your Spring MVC Controller" to Google

Categories
MVC , Controller , Test

Comments