Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test a ResponseBody or ResponseEntity sent by a spring mvc Controller?

When I do junit tests, I do something like this to test spring mvc controllers :

request.setRequestURI("/projects/"+idProject+"/modify");
ModelAndView mv = handlerAdapter.handle(request, response, controller);

where controller tested is like :

@RequestMapping(value = "{id}/modify")
public String content(ModelMap model, @PathVariable("id") Project object) {

But I don't find how to get the ResponseBody answer of request handlers defined like this :

@RequestMapping("/management/search")
public @ResponseBody ArrayList<SearchData> search(@RequestParam("q")) {
        ....
                ....
        ArrayList<SearchData> datas = ....;

        return datas;
    }
like image 592
Nico Avatar asked Mar 22 '11 15:03

Nico


People also ask

What is the difference between ResponseBody and ResponseEntity?

ResponseEntity represents an HTTP response, including headers, body, and status. While @ResponseBody puts the return value into the body of the response, ResponseEntity also allows us to add headers and status code.

How do you write a unit test for rest controller?

Writing a Unit Test for REST Controller First, we need to create Abstract class file used to create web application context by using MockMvc and define the mapToJson() and mapFromJson() methods to convert the Java object into JSON string and convert the JSON string into Java object.

Which class is used to test Spring MVC REST web application?

We create the test data by using a test data builder class. Configure our mock object to return the created test data when its findAll() method is invoked.


1 Answers

Your unit test only needs to verify the contents of the return value of the method:

ArrayList<SearchData> results = controller.search("value");
assertThat(results, ...)

The @ResponseBody annotation is irrelevant. This is one of the big benefits of annotated controllers - your unit tests can focus on the business logic, not the framework mechanics. With pre-annotation controllers, half of your test code is spent constructing mock requests, responses, and associated gubbins like that. It's a distraction.

Testing that your code's annotations integrate properly with the framework is the job of integration and/or functional tests.

like image 176
skaffman Avatar answered Nov 15 '22 06:11

skaffman