This is the fourth day of my participation in the First Challenge 2022.

In the process of project development, unit testing is always indispensable, whether it is the self-testing of functions or the creation of automated use cases. Unit testing is common for testing the logical functions of the Service layer, but also for the Controller layer, where you need to simulate request testing using JUnit’s Mcok objects.

1. @SpringBootTest

The @SpringBooTtest annotation loads the ApplicationContext and launches the Spring container. The SpringBootTest annotation automatically retrieves the application’s configuration file, starting with the current package. Look up the @SpringBootApplication annotation and @SpringBootConfiguration annotation class step by step.

Common configuration items in @SpringBoottest annotations are:

  • Value specifies the configuration attribute
  • Properties, which specifies the configuration property, has the same meaning as value
  • Classes, specifying the Configuration class, looks for the @Configuration class by default
  • WebEnviroment, specifying the Web environment, such as MOCK, RANDOM_PORT, DEFINED_PORT, and NONE

2. @runwith (JUnit4)

When a class is annotated with the @runWith annotation, or inherits from a class annotated with the @RunWith annotation, JUnit calls other classes referenced in the class to perform tests, rather than building within JUnit.

Common usage: @ RunWith (SpringJUnit4ClassRunner. Class)

In JUnit4, the @runWith annotation is not used in IDEA, and the unit tests can still run normally, because IDEA identifies a JUnit environment through @SpringbooTtest, which is equivalent to a self-identifying RunWith environment. This is not the case in other ides, so the @runwith annotation is still used in standard test classes.

  • Note: used in JUnit5@ExtendWith(SpringExtension.class)Instead of@RunWIthAnnotations, and no additional configuration is required in the SpringBoot environment because the @SpringBooTtest annotation already includes the @ExtendWith annotation

3. @Test

The @test annotation is used to mark a method as a unit Test method that can be executed separately

Similar method annotations in JUnit are:

  • @beforeall, executed once BeforeAll test methods are executed. The annotated method must be static
  • @beforeeach, executed once BeforeEach test method is executed, often used to initialize mockmvc objects before test method execution

4. Mock

In object-oriented programming, a mock object is a mock object that simulates the behavior of a real object in a controlled manner. In the process of programming, some input data is usually simulated to verify whether the program achieves the expected results.

  • With mock objects, you can simulate complex, real-world object behavior. If you cannot use real objects in unit tests, mock objects can be used instead.
  • The use of Mockito is generally divided into three steps: 1. 2. Execute test code; 3. Judge whether the execution results meet expectations.

4.1 MockMvc profile

MockMvc is provided by the Spring-test package, which implements the simulation of Http requests. It can directly use the network form and convert to the call of Controller, making the test fast and independent of the network environment. At the same time, a set of verification tools is provided to verify the result is very convenient.

4.2 Importing Dependencies

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
Copy the code
  • SpringBoot projects introduce spring-boot-starter-test by default, which contains MockMvc content.

4.3 Creating a MockMvc Object

  1. Build using MockMvcBuilder
    • The MockMvcBuilder interface provides a unique build method for constructing a MockMvc instance object.
    • MockMvc is instantiated in two ways
      • One is to use StandaloneMockMvcBuilder;
      • Another option is to use DefaultMockMvcBuilder.
private MockMvc mockMvc;

@Autowired
private MineController mineController;
@Autowired
private WebApplicationContext webApplicationContext;

@BeforeEach
public void setup(a) {
   // Instantiate method 1
   mockMvc = MockMvcBuilders.standaloneSetup(mineController).build();
   // Instantiate method 2
   // mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
Copy the code
  1. Create with annotations
  • Inject the MockMvc object directly using annotations
 @Autowired
 private MockMvc mockMvc;
Copy the code

4.4 Requesting Services

  1. MockMvc. Perform, executes a request and returns a ResultActions object
    • MockMvcRequestBuilders. Get/post (” XXX “) to construct a request
    • .contenttype (), sets the contentType
    • .accept(MediaType.TEXT_HTML_VALUE)) sets the return type
    • .param() to add the request pass value
    • .params(), adding request parameters in batches
    • .content(String content), set the request body content(jsonStr)
    • .header(), which sets the request header content
  2. Resultactions.andexpect (), which adds assertions after execution.
    • You can use MockMvcResultMatchers to verify the resulting content
    • AndExpect (MockMvcResultMatchers. The status (). Is4xxClientError ()), and return a status code 4 at the beginning of error
    • AndExpect (MockMvcResultMatchers. JsonPath ($. “errors”). The exists ()), return error nodes under the content
  3. Resultactions.anddo (), which adds a result handler to indicate what to do with the result
    • MockMvcResultHandlers. Print (), said the response output results information.
  4. Resultactions.andreturn (), which returns the MvcResult result object upon completion.
  5. Custom validation of returned results using assertions

5. Assertion

Assertions are used in unit tests to verify that test results match expectations and thus determine whether a unit test has passed.

  • The assertion method in JUnit5 isorg.junit.jupiter.api.AssertionsStatic methods in a class
  • The assertion method in JUnit4 isorg.junit.AssertStatic methods in a class

Common assertion methods

  • Assertions. AssertNull/assertNotNull, say whether the expected result is null
  • Assertions. AssertEquals/assertNotEquals assertion expected results and actual results are equal specified
  • Assertions. AssertTrue/assertFalse, assert that the expected results is true or false
  • Assertions assertArrayEquals, equal say whether expected results array with the specified array
  • AssertTimeout, Assertions whether the request time has timed out