6

Hi I'm new to Spring and to Junit as well. I have a method in my controller. I want to write Junit for this method (getPersons()).

@Autowired
private PersonService personService;

@RequestMapping(value="/t2/{yy_id}/person", method=RequestMethod.GET)
@ResponseBody
public PersonInfo[] getPersons() {

    return personService.getPersons();
}

Can someone please help me and guide me in a right manner. Please give some example.

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
Saurabh
  • 955
  • 6
  • 14
  • 22

1 Answers1

9

You should use the mvc test framework. It allows you to test all the mvc infrastructure - e.g. the @RequestMapping, @ResponseBody etc... - around your controller in addition to your own collaborators.

A very simple example of using the framework would be invoking the getPersons() method and asserting a 200 response code is received:

...
@Test
public void getPersons() throws Exception {
    this.mockMvc.perform(get("/t2/1234/person"))
      .andExpect(status().isOk());
}
...

The framework is capable of much more but I urge you to read the documentation, there are plenty of examples included. I hope that helps.

Jonathan
  • 20,053
  • 6
  • 63
  • 70
  • Hi Johnathan I agree with your answer and I have tried few things there but Still I'm facing some issues. I have updated my question can you tell me what wrong with it. – Saurabh Jun 20 '13 at 12:13
  • @Saurabh It would be better if you ask a new question. It's difficult to tell, however, ensure you have the correct static import declarations from `MockMvcResultMatchers` and `MediaType`. There are further [samples here](https://github.com/SpringSource/spring-mvc-showcase/tree/master/src/test/java/org/springframework/samples/mvc) that may help. – Jonathan Jun 20 '13 at 12:22