springboot2.x basic tutorial: unit testing

Unit testing is used to test individual code components and ensure that the code works as expected. Unit tests are written and executed by developers. In most cases, testing frameworks such as JUnit or TestNG are used. Test cases are usually written at the method level and executed through automation.
Spring Boot provides some annotations and tools to help developers test their applications.
Before talking about springboot unit testing, let's briefly introduce the types of software testing (from a development perspective) and how to write a unit test.

Software test type

  1. Unit testing: Used to test individual code components and ensure that the code works as expected. Unit tests are written and executed by developers.
  2. Integration test: Check whether the entire system is working properly. Integration testing is also done by developers, but instead of testing individual components, it aims to test across components. The system consists of many individual components, such as code, database, web server, etc. Integration testing can find problems such as component connection, network access, and database problems.
  3. Functional test: Check whether each feature is implemented correctly by comparing the result of the given input with the specification. This stage is usually handled by the company's dedicated testing team.
  4. Acceptance test: Acceptance test is to ensure that the software is ready, in accordance with the project contract, assignment statement, and the acceptance document agreed by both parties, to show the purchaser of the software the original requirements of the software.

Unit test points

  1. The granularity of the test is method level.
  2. The result of the test case should be stable.
  3. The test case should write as little logic as possible or not write test logic.
  4. Test cases should have a high coverage rate, covering basic input and output, and some boundaries should also be covered.
  5. Use assertions instead of outputting printed statements.
  6. The unit test case should have a good name, such as test_MethodName()

SpringBoot integration unit test

Introduce dependencies

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-test</artifactId>
	<scope>test</scope>
</dependency>

Dependency

  1. JUnit — The de-facto standard for unit testing Java applications.
  2. Spring Test & Spring Boot Test — Utilities and integration test support for Spring Boot applications.
  3. AssertJ — A fluent assertion library.
  4. Hamcrest — A library of matcher objects (also known as constraints or predicates).
  5. Mockito — A Java mocking framework.
  6. JsonPath — XPath for JSON

Common annotation description

  • @RunWith(SpringRunner.class)
    JUnit runs using Spring's test support. SpringRunner is the new name of SpringJUnit4ClassRunner. The purpose of doing so is just to make the name look simpler.
  • @SpringBootTest is
    used for Spring Boot application testing. By default, it will look up level by level according to the package name. It always finds the Spring Boot main program. It determines whether the main program is the main program by whether the class annotation contains @SpringBootApplication, and starts the class during testing. Create a Spring context environment.
  • @BeforeClass
    is executed only once for all tests and must be static void
  • @BeforeEach
    initialization method, executed before each test method of the current test class is executed
  • @Test
    test method, where you can test the expected exception and timeout
  • @AfterEach
    releases resources and executes each test method of the current test class
  • @AfterClass
    is executed only once for all tests and must be static void

  • Test methods ignored by @Ignore

Assertion common usage

  1. assertNotNull("message",A) //Judge A is not empty
  2. assertFalse("message",A) //Judgment condition A is not true
  3. assertTure("message",A) //Judging condition A is true
  4. assertEquals(“message”,A,B) // 判断A.equals(B)
  5. assertSame(“message”,A,B) //判断A==B

testing method

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserRepositoryTest  {
    @Autowired
    UserRepository userRepository;
    @Test
    @Ignore
    public void testFindAll(){
        Page<UserDO> userDOS= userRepository.findAll(PageRequest.of(1,10));
        Assert.assertNotNull(userDOS.getContent());
    }
    @Test(expected = RuntimeException.class)
    public void testNullPointerException(){
        throw new RuntimeException();
    }
}

Test API interface

  • MockMvcRequestBuilders
    constructs the request path, request parameters and other information
  • andExpect
    adds an assertion to determine whether the result meets expectations
  • andDo
    adds a result processor, such as the print in the example
  • andReturn
    returns the MvcResult after successful verification, which is used for custom verification/next step asynchronous processing.
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
class UserControllerTest {
    @Autowired
    MockMvc mockMvc;
    UserDO userDO;
    MultiValueMap<String,String> params;
    @BeforeEach
    public void setUp()throws Exception{
        userDO=new UserDO();
        userDO.setPasswd("123456");
        params=new LinkedMultiValueMap<>();
        params.add("name","codehome");
    }
	//测试get接口
    @Test
   public  void queryUser() throws Exception {
      String result= mockMvc.perform(MockMvcRequestBuilders.get("/user/query")
            .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .params(params)
        ).andExpect(MockMvcResultMatchers.status().is2xxSuccessful())
        .andDo(MockMvcResultHandlers.print())
                .andReturn().getResponse()
                .getContentAsString();
        Assert.assertEquals("调用成功","codehome",result);
    }
	//测试post接口
    @Test
    void addUser() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.post("/user/add")
            .contentType(MediaType.APPLICATION_JSON)
                .content(JsonUtil.toJson(userDO))
                .accept(MediaType.APPLICATION_JSON)
        ).andExpect(MockMvcResultMatchers.status().is2xxSuccessful())
                .andDo(MockMvcResultHandlers.print())
                .andExpect(MockMvcResultMatchers.jsonPath("$.data.passwd").value("123456"));
    }
	//测试cookie
    @Test
    void testCookie()throws Exception{
       String token= mockMvc.perform(MockMvcRequestBuilders.get("/user/cookie")
        .cookie(new Cookie("token","123456")))
                .andDo(MockMvcResultHandlers.print())
                .andReturn().getResponse()
                .getContentAsString();
       Assert.assertEquals("token从cookie中获取成功","123456",token);
    }
}
//测试的接口类
@RestController
@RequestMapping("/user")
public class UserController {
    @GetMapping("/query")
    public String queryUser(String name){
        return name;
    }
    @PostMapping("/add")
    public R addUser(@RequestBody UserDO userDO){
        return R.ok(userDO);
    }
    @GetMapping("/cookie")
    public String testCookie(@CookieValue("token") String token){
        return token;
    }
}

A thousand miles begins with a single step. This is the seventh article in the SpringBoot tutorial series. All project source codes can be downloaded on my GitHub . **

Guess you like

Origin blog.csdn.net/github_35592621/article/details/108248853