preface

After feature development is complete, the developers themselves do unit testing, although there are dedicated testers.

Companies generally have certain requirements for BUG rates and unit test coverage, so it is necessary to do unit testing well.

The backend provides interfaces, and this article uses MockMvc to simulate the interface for testing.

The specific implementation

Maven rely on

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
Copy the code

To prevent the test from impacting the real database data, the H2 database is used and the parameters are configured.

Parameter configuration

spring:
  datasource:
    driver-class-name: org.h2.Driver
    url: jdbc:h2:mem:test; MODE=MYSQL;
    schema: classpath:sqls/sys.sql
  main:
    banner-mode: off
mybatis:
  mapper-locations: classpath*:sql-mappers/**/*.xml
Copy the code
  • Spring.datasource. Schema specifies the construction statement file
  • Mybatis. Mapper-locations Specifies the mapper file

The sample

@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {

    @Autowired
    private MockMvc mvc;

    private static Gson gson = new GsonBuilder().serializeNulls().create();

    @Test
    @SqlGroup({
            @Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, value = "classpath:h2/user/init-data.sql"),
            @Sql(executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD, value = "classpath:h2/user/clean-data.sql")})void getUser(a) throws Exception {
        // Simulate a GET request
        mvc.perform(get("/user/1")
                // Request parameter type
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                // Receive parameter type
                .accept(MediaType.APPLICATION_JSON_UTF8))
                // Result verification
                .andExpect(status().isOk())
                .andExpect(jsonPath("code").value(200))
                .andExpect(jsonPath("data").exists())
                .andExpect(jsonPath("$['data']['account']").value("zhuqc1"))
                .andExpect(jsonPath("$['data']['password']").value("password"))
                .andExpect(jsonPath("$['data']['nickname']").value("zhuqc1"))
                .andExpect(jsonPath("$['data']['email']").value("[email protected]"))
                .andExpect(jsonPath("$['data']['phone']").value("13345678901"))
                // Result handler
                .andDo(MockMvcResultHandlers.print());
    }

    @Test
    @SqlGroup({
            @Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, value = "classpath:h2/user/init-data.sql"),
            @Sql(executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD, value = "classpath:h2/user/clean-data.sql")})void getUser2(a) throws Exception {
        // Simulate a GET request and return the result
        MvcResult result = mvc.perform(get("/user/1")
                .accept(MediaType.APPLICATION_JSON_UTF8))
                .andReturn();
        MockHttpServletResponse response = result.getResponse();
        JsonObject apiResult = JsonParser.parseString(response.getContentAsString()).getAsJsonObject();
        JsonObject data = apiResult.getAsJsonObject("data").getAsJsonObject();

        // Assert validation data
        Assertions.assertEquals(response.getStatus(), HttpStatus.OK.value());
        Assertions.assertEquals(data.get("account").getAsString(), "zhuqc1");
        Assertions.assertEquals(data.get("password").getAsString(), "password");
        Assertions.assertEquals(data.get("nickname").getAsString(), "zhuqc1");
        Assertions.assertEquals(data.get("email").getAsString(), "[email protected]");
        Assertions.assertEquals(data.get("phone").getAsString(), "13345678901");
    }

    @Test
    @SqlGroup({
            @Sql(executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD, value = "classpath:h2/user/clean-data.sql")})void addUser(a) throws Exception {
        User user = new User();
        user.setAccount("zhuqc1");
        user.setPassword("password");
        user.setNickname("zhuqc1");
        user.setEmail("[email protected]");
        user.setPhone("13345678901");

        // Simulate a POST request
        mvc.perform(post("/user")
                // Request parameter type
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                // Receive parameter type
                .accept(MediaType.APPLICATION_JSON_UTF8)
                // Request parameters
                .content(gson.toJson(user)))
                // Result verification
                .andExpect(status().isOk())
                .andExpect(jsonPath("code").value(200))
                .andExpect(jsonPath("data").value(1)); }}Copy the code
  • @springBooTtest Specifies that the test class runs in a SpringBoot environment

  • @AutoConfiguRemockMVC is used to automatically configure MockMvc, after which the MockMvc class can be injected directly

  • @sqlgroup Specifies the SQL statements before and after the test method is executed

    For example, data can be initialized before the test method is executed. After the test method is executed, clear the data.

MockMvc

MockMvc is the main entry for interface testing. The core method Perform (RequestBuilder) automatically executes SpringMVC’s process and maps it to the corresponding controller to perform processing. The method return value is ResultActions.

ResultActions

  • AndExpect Adds a ResultMatcher verification rule to verify whether the result is correct.
  • AndDo adds ResultHandler results handlers, such as printing results to the console.
  • AndReturn returns the result of the MvcResult execution, which can be customized for validation.

MockMvcResultMatchers

To verify that the execution results are correct, see the test method getUser().

MockMvcResultHandlers

Result handler, which means to do something with the result. See the test method getUser() for details.

Such as using MockMvcResultHandlers. Print () print the response result information to the console. As follows:

MvcResult

Unit test execution results that can be customized for validation, as shown in the test method getUser2().

The source code

Github.com/zhuqianchan…

Review past

  • Build backend frameworks from scratch – keep updating