Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 338
Saurabh Avatar asked Jun 20 '13 08:06

Saurabh


People also ask

What is JUnit testing in Spring Boot?

Spring Boot Rest Controller JUnit test cases example with Mockito. Unit tests are used to test the smaller units of an application. Unit tests make sure that a unit of code is working as expected. There are many unit testing frameworks available in Java. Example: TestNG, JUnit, Mockito, etc.

Is there any way to implement unit testing in spring?

It depends on what kind of test you want to implement. Certainly Spring Test helps in this. This module supports "unit" and integration testing. Note that unit tests are not really true unit tests because there is a little bit of context loading involved while using Spring Test at it's minimum.

How to test a spring controller?

There are many ways where we can test Spring controller. There is also a specific test framework, especially for Spring. Spring-Test is especially built for the Spring testing and we will be using it for the testing of the spring controller in our example below. Want to be a JUnit Master ?

How do I create a JUnit test class for a student controller?

Create a JUnit test class with the name StudentControllerTest.java under the /src/test directory. Add the code given below. import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;


1 Answers

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.

like image 134
Jonathan Avatar answered Sep 28 '22 08:09

Jonathan