Unit testing REST controllers
We have just tested a traditional controller redirecting to a view. Testing a REST controller is very similar in principle, but there are a few subtleties.
Since we are going to test the JSON output of our controller, we need a JSON assertion library. Add the following dependency to your build.gradle
file:
testCompile 'com.jayway.jsonpath:json-path'
Let's write a test for the SearchApiController
class, the controller that allows searching for a tweet and returns results as JSON or XML:
package masterSpringMvc.search.api; import masterSpringMvc.MasterSpringMvcApplication; import masterSpringMvc.search.StubTwitterSearchConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; ...
Get Spring MVC: Designing Real-World Web Applications now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.