简体   繁体   中英

How to test spring controller method using Junit

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.

You should use the mvc test framework . It allows you to test all the mvc infrastructure - eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM