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
Any questions about this give me a shout in the comments and I’ll explain anything I can.