This tutorial shows how to use Spring unit testing API and mock objects to test controllers which handle PUT requests.
Example
The controller
@Controller
@RequestMapping("/articles")
public class ArticleController {
//for xml and json
@PutMapping("/{id}")
@ResponseBody
public String createNewArticle(@RequestBody Article article) {
System.out.println("Creating Article in controller: " + article);
return "Article created.";
}
//for x-www-form-urlencoded
@PutMapping(value = "/{id}", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
@ResponseBody
public String createNewArticleWithFormParams(@RequestBody MultiValueMap<String, String> formParams) {
System.out.println("Creating Article in controller. MultiValueMap= " + formParams);
return "Article created.";
}
}
@XmlRootElement
public class Article {
private long id;
private String content;
.............
}
Java Config
@EnableWebMvc
@Configuration
@ComponentScan
public class MyWebConfig implements WebMvcConfigurer {
}
Unit Tests
Let's create and run our tests for XML, JSON and x-www-form-urlencoded requests one by one.
Testing XML PUT request
Running test ControllerPutTests.testXmlController() from the IDE:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = MyWebConfig.class)
public class ControllerPutTests {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
.............
@Test
public void testXmlController() throws Exception {
long id = 1;
MockHttpServletRequestBuilder builder =
MockMvcRequestBuilders.put("/articles/" + id)
.contentType(MediaType.APPLICATION_XML_VALUE)
.accept(MediaType.APPLICATION_XML)
.characterEncoding("UTF-8")
.content(getArticleInXml(1));
this.mockMvc.perform(builder)
.andExpect(MockMvcResultMatchers.status()
.isOk())
.andExpect(MockMvcResultMatchers.content()
.string("Article created."))
.andDo(MockMvcResultHandlers.print());
}
.............
private String getArticleInXml(long id) {
return "<article><id>" + id + "</id><content>test data</content></article>";
}
} Output Creating Article in controller: Article{id=1, content='test data'}
MockHttpServletRequest: HTTP Method = PUT Request URI = /articles/1 Parameters = {} Headers = {Content-Type=[application/xml;charset=UTF-8], Accept=[application/xml]} Body = <article><id>1</id><content>test data</content></article> Session Attrs = {}
Handler: Type = com.logicbig.example.ArticleController Method = public java.lang.String com.logicbig.example.ArticleController.createNewArticle(com.logicbig.example.Article)
Async: Async started = false Async result = null
Resolved Exception: Type = null
ModelAndView: View name = null View = null Model = null
FlashMap: Attributes = null
MockHttpServletResponse: Status = 200 Error message = null Headers = {Content-Type=[application/xml;charset=ISO-8859-1], Content-Length=[16]} Content type = application/xml;charset=ISO-8859-1 Body = Article created. Forwarded URL = null Redirected URL = null Cookies = []
Testing JSON PUT request
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = MyWebConfig.class)
public class ControllerPutTests {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
.............
@Test
public void testJsonController() throws Exception {
long id = 1;
MockHttpServletRequestBuilder builder =
MockMvcRequestBuilders.put("/articles/" + id)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.accept(MediaType.APPLICATION_JSON)
.characterEncoding("UTF-8")
.content(getArticleInJson(1));
this.mockMvc.perform(builder)
.andExpect(MockMvcResultMatchers.status()
.isOk())
.andExpect(MockMvcResultMatchers.content()
.string("Article created."))
.andDo(MockMvcResultHandlers.print());
}
.............
private String getArticleInJson(long id) {
return "{\"id\":\"" + id + "\", \"content\":\"test data\"}";
}
.............
} Output Creating Article in controller: Article{id=1, content='test data'}
MockHttpServletRequest: HTTP Method = PUT Request URI = /articles/1 Parameters = {} Headers = {Content-Type=[application/json;charset=UTF-8], Accept=[application/json]} Body = {"id":"1", "content":"test data"} Session Attrs = {}
Handler: Type = com.logicbig.example.ArticleController Method = public java.lang.String com.logicbig.example.ArticleController.createNewArticle(com.logicbig.example.Article)
Async: Async started = false Async result = null
Resolved Exception: Type = null
ModelAndView: View name = null View = null Model = null
FlashMap: Attributes = null
MockHttpServletResponse: Status = 200 Error message = null Headers = {Content-Type=[application/json;charset=ISO-8859-1], Content-Length=[16]} Content type = application/json;charset=ISO-8859-1 Body = Article created. Forwarded URL = null Redirected URL = null Cookies = []
Testing x-www-form-urlencoded PUT request
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = MyWebConfig.class)
public class ControllerPutTests {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
.............
@Test
public void testFormParamController() throws Exception {
String id = "1";
MockHttpServletRequestBuilder builder =
MockMvcRequestBuilders.put("/articles/" + id)
.contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.accept(MediaType.APPLICATION_FORM_URLENCODED)
.characterEncoding("UTF-8")
.content("id=" + id + "&content=test data");
this.mockMvc.perform(builder)
.andExpect(MockMvcResultMatchers.status()
.isOk())
.andExpect(MockMvcResultMatchers.content()
.string("Article created."))
.andDo(MockMvcResultHandlers.print());
}
.............
} Output Creating Article in controller. MultiValueMap= {id=[1], content=[test data]}
MockHttpServletRequest: HTTP Method = PUT Request URI = /articles/1 Parameters = {id=[1], content=[test data]} Headers = {Content-Type=[application/x-www-form-urlencoded;charset=UTF-8], Accept=[application/x-www-form-urlencoded]} Body = id=1&content=test data Session Attrs = {}
Handler: Type = com.logicbig.example.ArticleController
Async: Async started = false Async result = null
Resolved Exception: Type = null
ModelAndView: View name = null View = null Model = null
FlashMap: Attributes = null
MockHttpServletResponse: Status = 200 Error message = null Headers = {Content-Type=[application/x-www-form-urlencoded;charset=ISO-8859-1], Content-Length=[16]} Content type = application/x-www-form-urlencoded;charset=ISO-8859-1 Body = Article created. Forwarded URL = null Redirected URL = null Cookies = []
Example ProjectDependencies and Technologies Used: - spring-webmvc 5.0.3.RELEASE: Spring Web MVC.
- jackson-databind 2.9.4: General data-binding functionality for Jackson: works on core streaming API.
- spring-test 5.0.3.RELEASE: Spring TestContext Framework.
- junit 4.12: JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
- javax.servlet-api 3.0.1 Java Servlet API
- JDK 1.8
- Maven 3.3.9
|