While there are lots of articles around testing spring mvc, it took me a while to find all the info I needed to get my tests up and running, so I wanted to put down here for others to gain from and also for me to lookup when I inevitably forget something in the future.

My project is using maven and these dependencies are used by my tests:

<!-- Test -->
<!-- Jackson convertors -->

Then the method under test: MissingPersonsController

@RequestMapping(method=RequestMethod.GET, value={"/missing"})
public ResponseEntity list(@RequestParam(value="limit",required=false) Integer limit ) {
        List missing = mpDao.listAll();
	return this.responseHandler(missing);
    catch(Exception e){
	return this.responseHandler(new ArrayList(), HttpStatus.INTERNAL_SERVER_ERROR);

And now finally the Test:

@ActiveProfiles(profiles = "development")
public class TestMissingPersonsController extends TestCase {
	MissingPersonsController cont;
	AnnotationMethodHandlerAdapter adapter;
	MockHttpServletRequest request;
	MockHttpServletResponse response;
	ObjectMapper mapper;
	TypeReference> type = new TypeReference>() {};

	public void setUp(){
		adapter = new AnnotationMethodHandlerAdapter();
		request = new MockHttpServletRequest();
		response = new MockHttpServletResponse();
		mapper	= new ObjectMapper();
	public void testShouldGetResponse() {
		request.addHeader("x-auth-api", "abcd1234");
		 adapter.handle(request, response, cont);
		 assertEquals(200, response.getStatus());
		 Map converted = mapper.readValue(response.getContentAsString(), type);
		 assertEquals("application/json", response.getContentType());
		}catch(Exception e){



Any questions about this give me a shout in the comments and I’ll explain anything I can.

Sorry, the comment form is closed at this time.

© 2012 Craig Brookes Suffusion theme by Sayontan Sinha