Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test Spring mvc controller tests for response entity?

The controller is like:

    @RequestMapping(method = RequestMethod.GET, value = "/autocomplete")
    public ResponseEntity<String> autoComplete(@RequestParam("query") final String searchKey)
 {     
        List<String> list = ...     
        Gson gson = new Gson();
        String jsonString = gson.toJson(list);
        return new ResponseEntity<String>(jsonString, HttpStatus.OK);
  }

I couldn't find a way to test the ResponseEntity using Spring mvc controller. Could anyone help me with this?

like image 398
mon123 Avatar asked Oct 24 '16 04:10

mon123


People also ask

How do you write a Unit Test case for a Spring controller?

Unit Tests should be written under the src/test/java directory and classpath resources for writing a test should be placed under the src/test/resources directory. For Writing a Unit Test, we need to add the Spring Boot Starter Test dependency in your build configuration file as shown below.

Do we write test cases for controller?

It's definitely possible to write pure unit tests for Spring MVC controllers by mocking their dependencies with Mockito (or JMock) as jherricks showed above.

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.

What technique is used to Unit Test on a controller class?

We use a concept called test data builder when we are creating the test data for our test. Configure the used mock object to return the created test data when its findAll() method is called. Execute a GET request to url '/'. Ensure that the HTTP status code 200 is returned.


1 Answers

In spring integration test framework, it provides class MockMvc to test controllers.

MockMvc mvc = MockMvcBuilders.webAppContextSetup(wac).build(); // was is a web application context.
MvcResult result = mvc
            .perform(
                    get("/autocomplete")
            .accept(
                    MediaType.APPLICATION_JSON))
            .andExpect(status().isOk()).andReturn();
String content = result.getResponse().getContentAsString();  // verify the response string.
like image 119
Henry Avatar answered Oct 19 '22 00:10

Henry