In springmvc, the general test cases are testing the service layer. Today I will demonstrate how to use springmvc mock to directly test the controller layer code.
1.What is mock testing?
Mock testing is a test method that uses a virtual object to create for testing for certain objects that are not easy to construct or obtain during the testing process.
2. Why use mock test?
Testing with Mock Object is mainly used to simulate tools that are not easy to construct in applications (such as HttpServletRequest must be constructed in Servlet containers) or relatively complex objects (such as ResultSet objects in JDBC) so as to make the test go smoothly.
3. Common annotations
RunWith(SpringJUnit4ClassRunner.class): means using Spring Test components for unit testing;
WebAppConfiguration: Using this annotation will enable a web service when running unit tests, and then start calling the Controller's Rest API, and then stop the web service after the unit test is completed;
ContextConfiguration: There are many ways to specify the configuration file information of the bean. This example uses the file path form. If there are multiple configuration files, the information in brackets can be configured as a string array to represent it;
4. Install the test environment
The spring mvc test framework provides two ways: independently installing and integrating web environment testing (this method does not integrate the real web environment, but simulates and tests through the corresponding Mock API without starting the server).
Independent installation test method
MockMvcBuilders.standaloneSetup(Object... controllers): Specify a set of controllers through parameters, so that you do not need to get it from the context;
There are two main steps:
(1) First create the corresponding controller yourself and inject the corresponding dependencies
(2) Simulate a Mvc test environment through MockMvcBuilders.standaloneSetup, and obtain a MockMvc through build
The code is as follows:
package com.xfs.test;import org.junit.Assert;import org.junit.Before;import org.junit.Test;import org.springframework.test.web.servlet.MockMvc;import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;import org.springframework.test.web.servlet.result.MockMvcResultHandlers;import org.springframework.test.web.servlet.result.MockMvcResultMatchers;import org.springframework.test.web.servlet.setup.MockMvcBuilders;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import com.xfs.web.controller.APIController;/** * Independent installation test method springmvc mock test* * @author admin * * 10:39:49 am on November 23, 2017 */public class TestApiOne { private MockMvc mockMvc; @Before public void setUp() { APIController apiController = new APIController(); mockMvc = MockMvcBuilders.standaloneSetup(apiController).build(); } @Test public void testGetSequence() { try { MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/api/getSequence")) .andExpect(MockMvcResultMatchers.status().is(200)) .andDo(MockMvcResultHandlers.print()) .andReturn(); int status = mvcResult.getResponse().getStatus(); System.out.println("Request status code: " + status); String result = mvcResult.getResponse().getContentAsString(); System.out.println("Interface returns result: " + result); JSONObject resultObj = JSON.parseObject(result); // Determine whether the success field in the interface returns to json is true Assert.assertTrue(resultObj.getBooleanValue("success")); } catch (Exception e) { e.printStackTrace(); } }}The request result is as follows:
Integrated Web environment
MockMvcBuilders.webAppContextSetup(WebApplicationContext context): Specify WebApplicationContext, and the corresponding controller will be obtained from the context and the corresponding MockMvc will be obtained;
There are three main steps:
(1) @WebAppConfiguration: Used in the test environment, which means that the ApplicationContext used in the test environment will be of type WebApplicationContext; value specifies the root of the web application;
(2) Through @Autowired WebApplicationContext wac: ApplicationContext container injected into the web environment
(3) Then create a MockMvc through MockMvcBuilders.webAppContextSetup(wac).build() for testing
The code is as follows:
package com.xfs.test;import org.junit.Assert;import org.junit.Before;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.mock.web.MockHttpSession;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;import org.springframework.test.context.web.WebAppConfiguration;import org.springframework.test.web.servlet.MockMvc;import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;import org.springframework.test.web.servlet.result.MockMvcResultHandlers;import org.springframework.test.web.servlet.result.MockMvcResultMatchers;import org.springframework.test.web.servlet.setup.MockMvcBuilders;import org.springframework.web.context.WebApplicationContext;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;/** * Integrated Web Environment Method springmvc mock test* * @author admin * * November 23, 2017 at 11:12:43 am */@RunWith(JUnit4ClassRunner.class)@WebAppConfiguration@ContextConfiguration(locations = { "classpath*:spring/*.xml" })public class TestApiTwo extends AbstractJUnit4SpringContextTests { @Autowired public WebApplicationContext wac; public MockMvc mockMvc; public MockHttpSession session; @Before public void before() throws Exception { mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); } @Test public void testGetSequence() { try { MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/api/getSequence")) .andExpect(MockMvcResultMatchers.status().is(200)) .andDo(MockMvcResultHandlers.print()) .andReturn(); int status = mvcResult.getResponse().getStatus(); System.out.println("Request status code: " + status); String result = mvcResult.getResponse().getContentAsString(); System.out.println("Interface returns result: " + result); JSONObject resultObj = JSON.parseObject(result); // Determine whether the success field in the interface returns json is true Assert.assertTrue(resultObj.getBooleanValue("success")); } catch (Exception e) { e.printStackTrace(); } }}The results of the run are the same as those of the above independent test.
Summarize:
The whole process:
1. mockMvc.perform executes a request;
2. MockMvcRequestBuilders.get("/user/1") constructs a request
3. ResultActions.andExpect adds assertions after execution
4. ResultActions.andDo adds a result processor to indicate what to do with the result. For example, use MockMvcResultHandlers.print() to output the entire response result information.
5. ResultActions.andReturn means that the corresponding result is returned after the execution is completed.
The whole test process is very regular:
1. Prepare for the test environment
2. Execute requests through MockMvc
3. Add verification assertion
4. Add a result processor
5. Get MvcResult for custom assertions/make the next asynchronous request
6. Uninstall the test environment
Reference: spring-mvc-test-framework
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.