Location>code7788 >text

Spring Unit Test (I) Introduction and Practice

Popularity:783 ℃/2025-02-17 17:33:03

Question: How to test quickly instead of restarting the app every time you test?
Target:Try to test only local code

Different tests

Software engineering is divided into: unit testing, integration testing, functional testing, and system testing. Among them, functional testing and system testing are generally the responsibility of the tester, but unit testing and integration testing must be guaranteed by the developer.

  • Functional testing: Check whether the requirements determined in the requirements manual are met.
  • System testing: combined with other system functions for testing
  • Unit Testing: Check a small piece of code written by the developer to confirm that the changes are correct.
    A function often calls multiple interface methods to implement it. During unit testing, it is necessary to block the dependencies of these external interface methods and focus the test on the target function code. For example, the public method of the underlying tool class DateUtils has been changed.

At this time, simulation is the most powerful tool. It simulates the process of using functions. Assuming that the external interface method returns normally, verify the correctness of the target code. Common simulation tools are EasyMock, JMock, and Mockito.

The most important thing about unit testing is repeatability. Unit testing that is non-repeatable is of no value.

Unit testing and development work are carried out simultaneously, sometimes even before development work.

  • Integration testing is to verify whether the function modules can be called normally after the functional development code is developed.

For example, when unit testing the UserService business layer class, you can create a UserDao mock object and perform local unit testing on the UserService under the assumption that the DAO layer interface method works normally.

When performing integration testing on UserService, the real UserDao object should be injected.
So generally speaking, integration testing is higher in terms of levels, and the business layer and web layer are generally integrated testing; unit testing is aimed at some classes with single functions, such as string formatting tools, data calculation classes, etc.

Test framework

Spring-Test is a module in springframework and is a unit test suite provided by Spring, which can easily test code based on the Spring framework.

Spring-Test is an extension of the Spring framework. It is specially used to help test Spring applications. It is built on Junit and provides Spring container-related functions, such as testing the life cycle of Spring Beans, Spring configuration loading, etc.

Code Practice

1. Introduce dependencies

<!-- Unit Test -->
 <dependency>
 <groupId></groupId>
 <artifactId>spring-test</artifactId>
 <version>5.2.</version>
 <scope>test</scope>
 </dependency>
 <dependency>
 <groupId></groupId>
 <artifactId>mockito-core</artifactId>
 <version>3.11.2</version>
 <scope>test</scope>
 </dependency>
 <dependency>
 <groupId></groupId>
 <artifactId>mockito-inline</artifactId>
 <version>3.11.2</version>
 <scope>test</scope>
 </dependency>
 <dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>4.13.2</version>
 <scope>test</scope>
 </dependency>

2. Interface testing

/**
  * Favor interface unit test
  */
 @RunWith()
 public class FavorControllerTest {
     private MockMvc mockMvc;
     @Mock
     private FavorService favorService;
     @Mock
     private PersonService personService;
     @InjectMocks
     private FavorController favorController;

     @Before
     public void setup() {
         mockMvc = (favorController).build();
         // Simulate login users
         MockedStatic<SessionUtils> sessionUtils = mockStatic();
         User mockUser = new User();
         (1L);
         ("testUser");
         (SessionUtils::currentUser).thenReturn(mockUser);
     }

     /**
      * Test whether the request message is legal
      *
      * @throws Exception
      */
     @Test
     public void listPage_ValidQuery_ShouldReturnFavorList() throws Exception {
         // Simulate query results
         List<Favor> favorList = new ArrayList<>();
         Favor favor = new Favor();
         (1L);
         (1L);
         (favor);
         // Simulate business layer paging query
         when((any())).thenReturn(favorList);
         // Simulation query personnel
         Person mockPerson = new Person();
         (1L);
         when((1L)).thenReturn(mockPerson);
         // Simulate Http request
         String requestBody = "{\"terms\":{\"title\":\"someValue\"},\"page\":{\"pageNo\":1,\"pageSize\":10}}"  ;
         (post("/favor/listPage")
                 .contentType(MediaType.APPLICATION_JSON)
                 .content(requestBody))
                 .andExpect(status().isOk());
     }
 }

For the sake of concise writing, the implementation of some codes such as FavorController and FavorService that are ignored will not affect the explanation.

Note: This code is to test the legality of the request message, that is, whether the requested response code is 200, provided that when the interface verifies that the request message is illegal, it will return a response code other than 200.

Different test goals will also be different.

3. DAO layer testing

/**
  * DAO layer test
  */
 @Slf4j
 @RunWith()
 @ContextConfiguration(locations = {"classpath:"})
 @Transactional
 public class FavorItemDaoTest {

     @Autowired
     private FavorItemDao favorItemDao;

     @Before
     public void setUp() {
         // If necessary, any common settings can be made here
     }

     /**
      * Test query conditions
      */
     @Test
     public void findByCondition_related() {
         Map<String, Object> map = ("receiveGiveRelated", true,
                 "receivePersonIdList", (1L, 2L, 3L, 4L),
                 "givePersonIdList", (11L, 12L));
         List<FavorItem> byCondition = (map);
         assertNotEquals(0, ());
     }

 }

The Spring configuration file here is recommended to be as concise as possible to speed up the execution of the test method.