[Java] What is unit testing?

1. What is unit testing? step

Unit Testing is a testing method in software development that is used to ensure that a single unit of code (such as a function or method) operates as expected. By writing unit tests, developers can check that each unit of code independently produces the correct results. Unit testing helps identify and fix errors in the code, thereby improving software quality.
Typically, the steps for a unit test are as follows:

  1. Writing test cases: Write a set of test cases for a unit of code, each containing specific inputs and expected outputs.
  2. Run tests: Run the written unit tests using a test framework, which can usually automatically execute all test cases and report the results.
  3. Check results: The testing framework reports the pass or fail status of each test case. If a test case fails, it means there is a problem with the unit of code that needs to be debugged and fixed.
  4. Fix code: For failed test cases, developers need to investigate the cause of the error and modify the corresponding code to make the test pass.
  5. Repeat the tests: After fixing the code, run all test cases again to ensure that the fixed code did not introduce new errors.
  6. The main purpose of unit testing is to ensure the reliability, stability and maintainability of the code. By writing and executing unit tests, developers can find and fix bugs in the early stages of a project, thus avoiding difficult-to-troubleshoot problems later in the project.

2. Simple unit operation, Demo

To implement unit testing in Spring Boot, the steps are as follows:

  1. Add dependencies:
    pom.xml
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
  1. Write a test class: Create a test class corresponding to the class to be tested. The test class should be in the same package as the class being tested and follow the naming convention, eg YourClassTest. In the test class, use @RunWith(SpringRunner.class) annotations to specify the test runner and use @SpringBootTestannotations to enable Spring Boottest functionality.
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class YourClassTest {
    
    
    // 编写测试用例
}
  1. Write test cases: In the test class, write one or more test cases for each method you want to test. Use JUnit @Testannotations to mark test methods. You can use assertions (such as assertEquals, assertTrueetc.) to verify that the output of a method is as expected.
import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class YourClassTest {
    
    
    @Test
    public void testYourMethod() {
    
    
        YourClass yourClass = new YourClass();
        int expectedResult = 42;
        int actualResult = yourClass.yourMethod();
        assertEquals(expectedResult, actualResult);
    }
}
  1. Run the test. If any test case fails, modify the corresponding implementation code and rerun the test until all test cases pass.

Add another example:
for example, HelloController, test/hello, write a test class:

@RunWith(SpringRunner.class)
@WebMvcTest(HelloController.class)
public class HelloControllerTest {
    
    
    @Autowired
    private MockMvc mockMvc;
    @Autowired
    private ServletContext servletContext;

    @Test
    public void test1() throws Exception{
    
    
        MvcResult end = mockMvc.perform(requestBuilder("/hello"))
                .andExpect(mvcResult -> {
    
    
                    if (mvcResult.getResponse().getStatus() != 200) {
    
    
                        throw new RuntimeException("failed.");
                    }
                })
                .andExpect(result -> {
    
    
                    if (!result.getResponse().getContentType().contains("json")) {
    
    
                        throw new RuntimeException("failed");
                    }
                }).andReturn();

        System.out.println(end);
    }

    private RequestBuilder requestBuilder(String uri) {
    
    
        return MockMvcRequestBuilders.get(URI.create(uri)).accept(MediaType.APPLICATION_JSON_UTF8)
                .characterEncoding("UTF-8");
    }
}

Supplement: In actual projects, you may encounter some highly coupled business methods, and you will be in pain at this time. For example: there are too many input parameters and there are too many equivalence classes for parameters, which should be avoided during design.
Solution:
1. Use global variables/object properties for output to minimize mutual calls of functions.
2. Separate the I/O operations of the module to reduce function calls.
3. Encapsulate the function call and do not call it during testing. Instead, the function ID and parameters are output through global variables.
4. When input is obtained through function calls, the input is also encapsulated as function ID and global variables.

3. What is piling?

Stubbing in unit testing is a testing technique used to replace the behavior of actual components (such as methods, objects, or services) during testing. Stubbing is often used to mock certain parts of the code in order to control their behavior during testing. This allows you to focus on testing the target method or class without worrying about external dependencies or the impact of other components.

The main advantages of piling are:

  1. 打桩Isolation: Isolate the unit of code to be tested by using it so that it is not interfered with by external dependencies or other components. This ensures that unit tests focus only on the functionality of the target code, rather than the behavior of the entire system.
  2. Controllable: Piling allows the behavior of replacement components to be predefined. This means the output of these components can be precisely controlled during testing, making it easier to test different scenarios and boundary conditions.
  3. Simplification: Sometimes, the actual components can be complex or difficult to set up. By using stubbing, you can replace these components with simple, easy-to-manage mock objects, simplifying the testing process.

To implement stubbing in unit tests, you can use some mocking frameworks like Mockitoetc.
Here is a Mockitosimple example of piling using:

import org.junit.Test;
import org.mockito.Mockito;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;

public class YourClassTest {
    
    
    @Test
    public void testYourMethodWithStub() {
    
    
        // 创建一个依赖类的模拟对象
        DependencyClass mockDependency = Mockito.mock(DependencyClass.class);

        // 为模拟对象的某个方法设置预期行为(打桩)
        when(mockDependency.someMethod()).thenReturn("stubbedValue");

        // 将模拟对象传递给要测试的类
        YourClass yourClass = new YourClass(mockDependency);

        // 调用要测试的方法
        String expectedResult = "expectedResult";
        String actualResult = yourClass.yourMethod();

        // 验证结果
        assertEquals(expectedResult, actualResult);
    }
}

In this example, we create a mock object using , and set the expected behavior for its Mockitomethods . We then pass the mock object to , and execute the test. This way we ensure that the test only focuses on the behavior and is not affected by the actual implementation.DependencyClasssomeMethodYourClass
YourClassDependencyClass

If there are any mistakes, please let me know!
When reprinting or quoting the content of this article, please indicate the source and original author: Juzu Qingzhong;

Guess you like

Origin blog.csdn.net/weixin_44510587/article/details/129867314