SoFunction
Updated on 2025-03-08

SpringMVC Mock test implementation principle and implementation process detailed explanation

What is mock testing?

During the testing process, for some objects that are not easy to form or are not easy to obtain, a virtual object is created for testing, which is Mock testing.

Servlet, Request, Response and other Servlet API related objects are originally created by the Servlet container (Tomcat).

This virtual object is a Mock object.

Mock objects are a substitute for real objects during debugging.

Why use Mock test?

  • Avoid coupling between development modules
  • Lightweight, simple and flexible

Introduction to MockMVC

MockMvcBuilder

It is the constructor used to construct MockMVC

There are two main implementations: StandaloneMockMvcBuilder and DefaultMockMvcBuilder, which correspond to the previous two test methods.

We can create it directly using the static factory MockMvcBuilders.

MockMvcBuilders

Responsible for creating MockMvcBuilder object

There are two ways to create

1、standaloneSetup(Object... controllers)

2. webAppContextSetup(WebApplicationContext wac): Specify WebApplicationContext, and the corresponding controller will be obtained from the context and the corresponding MockMvc will be obtained.

MockMvc

Main entry point is supported for Spring MVC testing on the server side.

Constructed by MockMvcBuilder

MockMvcBuilder is constructed by the static method of MockMvcBuilders.

Core method: perform(RequestBuilder requestBuilder)--->Execute a RequestBuilder request, which will automatically execute SpringMvc process and map it to the corresponding controller to perform processing. The return value of this method is a ResultActions;

ResultActions

andExpect

Add ResultMatcher verification rules to verify whether the results are correct after the controller is executed.

andDo

Add a ResultHandler result processor, such as printing the results to the console during debugging;

andReturn

Finally, the corresponding MvcResult is returned; then custom verification/the next step of asynchronous processing is performed.

MockMvcRequestBuilders

  • Used to construct requests
  • It mainly consists of two subclasses, MockHttpServletRequestBuilder and MockMultipartHttpServletRequestBuilder (such as file upload), which is used by the Mock client to request all the data required.

MockMvcResultMatchers

  • Used to match the result verification after executing the request
  • If the match fails, the corresponding exception will be thrown
  • Includes many verification API methods

MockMvcResultHandlers

  • The result processor indicates that you want to do something to the result
  • For example, use() here to output the entire corresponding result information.

MvcResult

Unit test execution results, you can customize verification logic for execution results.

Use of MocMvc

Add dependencies

    <!-- spring Unit Test Component Package -->
    <dependency>
      <groupId></groupId>
      <artifactId>spring-test</artifactId>
      <version>5.0.</version>
    </dependency>
 
    <!-- Unit TestingJunit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>

Test class

package ;

import ;
import ;
import ;
import ;
import ;
import .junit4.SpringJUnit4ClassRunner;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

//@WebAppConfiguration: You can get a Web application context without starting the Servlet container during unit testing@RunWith()
@ContextConfiguration(locations = "classpath:spring/*.xml")
@WebAppConfiguration
public class TestMockMVC {
  @Autowired
  private WebApplicationContext wac;
  private MockMvc mockMvc;

  @Before
  public void Setup() {
    // There are two ways to initialize a MockMVC object: separate settings and web application context settings.    // It is recommended to use web application context settings    mockMvc = new MockMvcBuilders().webAppContextSetup(wac).build();
  }

  @Test
  public void test() throws Exception {
    // Execute an Http request through perform    // andExpect: Through this method, determine whether the request execution is successful    // andDo: output the result after the request    MvcResult result = (("/item/showEdit").param("id", "1"))
        .andExpect(().name("item/item-edit"))
        .andExpect(().isOk())
        .andDo(())
        .andReturn();
    ("===============");
    (());
  }
}

The operation results are as follows

JRE Oracle Corporation/13.0.1 is not supported, advanced source lookup disabled.
12moon 12, 2019 4:48:43 afternoon  getDefaultTestExecutionListenerClassNames
information: Loaded default TestExecutionListener class names from location [META-INF/]: [, , , , , ]
12moon 12, 2019 4:48:43 afternoon  getTestExecutionListeners
information: Using TestExecutionListeners: [@4470f8a6, @7c83dc97, @7748410a, @740773a3, @37f1104d, @55740540]
12moon 12, 2019 4:48:43 afternoon  loadBeanDefinitions
information: Loading XML bean definitions from file [D:\JAVA\eclipse_setup\ssm-project\target\classes\spring\]
12moon 12, 2019 4:48:43 afternoon  loadBeanDefinitions
information: Loading XML bean definitions from file [D:\JAVA\eclipse_setup\ssm-project\target\classes\spring\]
12moon 12, 2019 4:48:43 afternoon  loadBeanDefinitions
information: Loading XML bean definitions from file [D:\JAVA\eclipse_setup\ssm-project\target\classes\spring\]
12moon 12, 2019 4:48:43 afternoon  loadBeanDefinitions
information: Loading XML bean definitions from file [D:\JAVA\eclipse_setup\ssm-project\target\classes\spring\]
12moon 12, 2019 4:48:43 afternoon  prepareRefresh
information: Refreshing @50ad3bc1: startup date [Thu Dec 12 16:48:43 CST 2019]; root of context hierarchy
12moon 12, 2019 4:48:44 afternoon $MappingRegistry register
information: Mapped "{[/item/updateItem],produces=[application/json;charset=utf8]}" onto public  (,,,,) throws 
12moon 12, 2019 4:48:44 afternoon $MappingRegistry register
information: Mapped "{[/item/testRedirect],produces=[application/json;charset=utf8]}" onto public  ()
12moon 12, 2019 4:48:44 afternoon $MappingRegistry register
information: Mapped "{[/item/testForward],produces=[application/json;charset=utf8]}" onto public  ()
12moon 12, 2019 4:48:44 afternoon $MappingRegistry register
information: Mapped "{[/item/findItem],produces=[application/json;charset=utf8]}" onto public  ()
12moon 12, 2019 4:48:44 afternoon $MappingRegistry register
information: Mapped "{[/item/queryItem],produces=[application/json;charset=utf8]}" onto public  () throws 
12moon 12, 2019 4:48:44 afternoon $MappingRegistry register
information: Mapped "{[/item/queryItem2],produces=[application/json;charset=utf8]}" onto public  .queryItem2()
12moon 12, 2019 4:48:44 afternoon $MappingRegistry register
information: Mapped "{[/item/deleteItem],produces=[application/json;charset=utf8]}" onto public void ([])
12moon 12, 2019 4:48:44 afternoon $MappingRegistry register
information: Mapped "{[/item/saveItem],produces=[application/json;charset=utf8]}" onto public  ()
12moon 12, 2019 4:48:44 afternoon $MappingRegistry register
information: Mapped "{[/item/showEdit],produces=[application/json;charset=utf8]}" onto public  ()
12moon 12, 2019 4:48:44 afternoon $MappingRegistry register
information: Mapped "{[/item/batchUpdateItem],produces=[application/json;charset=utf8]}" onto public <> ()
12moon 12, 2019 4:48:44 afternoon $MappingRegistry register
information: Mapped "{[/queryItemByIdWithRest]}" onto public  ()
12moon 12, 2019 4:48:44 afternoon  initControllerAdviceCache
information: Looking for @ControllerAdvice: @50ad3bc1: startup date [Thu Dec 12 16:48:43 CST 2019]; root of context hierarchy
12moon 12, 2019 4:48:44 afternoon  initControllerAdviceCache
information: Looking for @ControllerAdvice: @50ad3bc1: startup date [Thu Dec 12 16:48:43 CST 2019]; root of context hierarchy
12moon 12, 2019 4:48:44 afternoon  log
information: Initializing Spring FrameworkServlet ''
 December 12, 2019 4:48:44 pm initServletBean
 Information: FrameworkServlet '': initialization started
 December 12, 2019 4:48:44 pm initServletBean
 Information: FrameworkServlet '': initialization completed in 17 ms
@1ad9b8d3

MockHttpServletRequest:
HTTP Method = GET
Request URI = /item/showEdit
Parameters = {id=[1]}
Headers = {}
Body = <no character encoding set>
Session Attrs = {}

Handler:
Type = 
Method = public  ()

Async:
Async started = false
Async result = null

Resolved Exception:
Type = null

ModelAndView:
View name = item/item-edit
View = null
Attribute = item
value = @1ad9b8d3
errors = []

FlashMap:
Attributes = null

MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Language=[en]}
Content type = null
Body =
Forwarded URL = /WEB-INF/jsp/item/
Redirected URL = null
Cookies = []
===============
public  ()

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.