How to use JUnit to test the spring controller method

Hi, I'm new to spring and JUnit There is a method in my controller I want to write JUnit (getpersons ()) for this method

@Autowired
private PersonService personService;

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

    return personService.getPersons();
}

Someone can help me and guide me in the right way Please give an example

Solution

You should use MVC test framework It allows you to test all MVC infrastructure - such as @ requestmapping, @ ResponseBody... - around your controller in addition to your own collaborators

A very simple example of using the framework is to call the getpersons () method and declare that the 200 response code is received:

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

The framework can do more, but I urge you to read the documentation, which contains a large number of examples I hope it helps

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>