mockMvc Tutorial

1. Mock Test Introduction

  • Is defined
    in the cell test, some not easily configured for the object or not easily accessible, using a method of creating a virtual object for testing.
  • Why mock test
    • Avoid coupling between the module development;
    • Lightweight, simple and flexible;

2. MockMVC Introduction

Based tests for RESTful SpringMVC unit can test the complete SpringMVC process, i.e., from the URL request to the control processor, can be tested to the view rendering.

2.1 MockMvc

  • SpringMVC test server main entry point.
  • By static method MockMVCBuilders builders to build MockMVCBuilder, MockMvc by the MockMVCBuilder structure.
  • Core Method: Perform (RequestBuilder RB), a RequestBuilder Please perform, automatically executes SpringMVC and mapped to the corresponding process controller executes processing, the return value is a ResultActions.

2.2 MockMVCBuilder

  • MockMVCBuilder configured by using the model builder to construct MockMvc.
  • There are two implementations: StandaloneMockMvcBuilder and DefaultMockMvcBuilder .
  • You can directly use the static factory MockMvcBuilders created , do not need the direct use of the above two implementation classes.

2.3 MockMVCBuilders

  • MockMVCBuilder responsible for creating objects.
  • There are two ways to create
    • standaloneSetup (Object ... controllers): parameter specifies a set of controllers, so that no acquired from the context.
    • webAppContextSetup (the WebApplicationContext WAC): Specifies WebApplicationContext, will be acquired from the respective controller and to give the corresponding context MockMvc

2.4 MockMvcRequestBuilders

  • Request for constructing the request.
  • There are two major subclasses MockHttpServletRequestBuilder and MockMultipartHttpServletRequestBuilder (such as file uploads use), i.e., all client requests for data Mock required.

2.5 ResultActions

  • andExpect : Add ResultMatcher validation rules, verify the controller performs complete results are correct.
  • andDo : Add ResultHandler result processor, such as printing to the console when debugging.
  • andReturn : finally returns the corresponding MvcResult ; custom authentication and / asynchronous processing of the next step.
  • MockMvcResultMatchers
    • ** to match the result of executing the request for verification.
    • If the match fails will throw an appropriate exception.
    • It contains a lot of validation API methods.
  • MockMvcResultHandlers
    • The results processor, pledged to do something with the results.
    • As used herein, such MockMvcResultHandlers.print () result information in response to the output of the whole.

2.6 MvcResult

Unit test execution, results may be performed for a custom validation logic . The use of assertions to verify the data.

code show as below:

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.json.JSONArray;
import org.json.JSONObject;
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.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import com.boke.Application;



/**
 * Use the presentation MockMVC
 * @author zenglingsheng
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
@SpringBootTest(classes=Application.class)
public class NewApiControllerTest {
    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void setUp() throws Exception {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }
   
    
    @Test
    public void testEquipmenttypes() throws Exception {
        MvcResult authResult = null ;
        authResult = mockMvc.perform (get ( "/ API / WorkItem / equipmenttypes") // Use way to get call interface. 
                .contentType (MediaType.APPLICATION_XHTML_XML) // Type of request parameter 
                .param ( "sessionid", "ZlbpLxXw ") // request parameter (-s) 
        ) .andExpect (Status (). ISOK ())
                .andReturn();
        // get the data 
        the JSONObject jsonObject = new new   the JSONObject (authResult.getResponse () getContentAsString ().);
        JSONArray jsonArrayData = (JSONArray)jsonObject.get("data");
        
        // get value of the first Array that judgment to the query results. 
        = JsonObject_data the JSONObject null ;
         IF (jsonArrayData.length ()> 0 ) {
            jsonObject_data = (JSONObject) jsonArrayData.get(0);
        }
        // add asserted that judgment property values. 
        Assert.assertNotNull (jsonObject.get ( "ERROR_CODE" ));
        Assert.assertEquals(jsonObject.get("error_code"),0);
        Assert.assertNotNull(jsonObject.get("error_msg"));
        Assert.assertEquals(jsonObject.get("error_msg"),"操作成功");
        Assert.assertNotNull(jsonObject.get("data"));
        Assert.assertNotNull(jsonObject_data);
        Assert.assertEquals(jsonObject_data.get("equipmentty"),1);
        Assert.assertEquals(jsonObject_data.get("equipmenttypename"),"xxxxx");
        
   
    }
}

This is in accordance with the specific format of the item being tested, test data, test data to the bottom. Meng new one, do not spray the great God.

 

Related article: https: //www.jianshu.com/p/94e5de3f28c9

 

Guess you like

Origin www.cnblogs.com/zengls/p/11316454.html