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 -->
<dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>4.7</version>
   <scope>test</scope>
</dependency> 
<!-- Jackson convertors -->
<dependency>
  <groupId>org.codehaus.jackson</groupId>
  <artifactId>jackson-mapper-lgpl</artifactId>
  <version>1.9.1</version>
</dependency>
<dependency>
  <groupId>org.codehaus.jackson</groupId>
  <artifactId>jackson-core-lgpl</artifactId>
  <version>1.9.1</version>
</dependency> 

Then the method under test: MissingPersonsController

@RequestMapping(method=RequestMethod.GET, value={"/missing"})
public ResponseEntity list(@RequestParam(value="limit",required=false) Integer limit ) {
  try{
        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:


@ContextConfiguration(locations="classpath:/test-context.xml")
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles(profiles = "development")
public class TestMissingPersonsController extends TestCase {
	
	@Resource
	MissingPersonsController cont;
	
	AnnotationMethodHandlerAdapter adapter;
	MockHttpServletRequest request;
	MockHttpServletResponse response;
	ObjectMapper mapper;
	TypeReference> type = new TypeReference>() {};

	@Before
	public void setUp(){
		adapter = new AnnotationMethodHandlerAdapter();
		request = new MockHttpServletRequest();
		response = new MockHttpServletResponse();
		mapper	= new ObjectMapper();
	}
	
	@Test
	public void testShouldGetResponse() {
		
		request.setMethod("GET");
		request.setRequestURI("/missing");
		request.addHeader("x-auth-api", "abcd1234");
		
		try{
		 adapter.handle(request, response, cont);
		 assertEquals(200, response.getStatus());
		 Map converted = mapper.readValue(response.getContentAsString(), type);
		 assertEquals("application/json", response.getContentType());
		 assertEquals(converted.get("message"),"OK");
		
		}catch(Exception e){
			e.printStackTrace();
			fail(e.getMessage());
		}

	}

}

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