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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With