This is my first article on getting started

Unit test is the code that tests the function of a certain function or a certain module in the program. It is generally written by the developer during the development of the code. Through unit test, the bugs of the code logic can be exposed as early as possible and the correctness of the code can be guaranteed at a smaller granularity.

Have you heard of TEST-driven Development (TDD)? “Test-driven Development” (TDD) refers to unit testing as the first step in coding. The first step is to complete a unit Test, and the Test will fail or even fail to compile due to the lack of functional code. Then develop functional code until the unit tests you just wrote pass; Then write the test code for another function, and iterate until the code is finished.

Personally, I think TDD is a good development process, which can ensure the coverage of unit tests. However, TDD may be difficult in the actual practice. My personal habit is to write functional logic first, and then write unit tests for testing:)

Let me show you how to write unit tests to test the functional code we write in a Spring Boot project.

Spring Boot Test configuration

  • Spring Boot project configuration

    Add a spring-boot-starter-test dependency to the Spring Boot project. After Spring Boot 2.4, the spring-boot-starter-test dependency is Junit5. You can add dependencies for Junit4 separately

    Maven pom.xml:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.vintage</groupId>
        <artifactId>junit-vintage-engine</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.hamcrest</groupId>
                <artifactId>hamcrest-core</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    Copy the code

    Gradle build.gradle:

    testCompile 'org.springframework.boot:spring-boot-starter-test'
    testCompile group: 'junit', name: 'junit', version: '4.12'
    Copy the code

Spring Boot tests the Demo

Suppose we have an AddServer in our Spring Boot project that implements the addition of two numbers. Its interface and implementation are as follows:

public interface AddService {
  long add(long a, long b);
}

@Service
public class AddServiceImpl implements AddService {
  public long add(long a, long b) {
    returna + b; }}Copy the code

The test class for the add method is as follows:

@RunWith(SpringRunner.class)
@SpringBootTest
public class AddServiceTest {
	@Autowired
	private AddService addService;
	
	@Test
	private void addTest(a){
		Assert.assertEquals(2, addService.add(1.1)); }}Copy the code

RunWith(Springrunner.class) provides a bridge between The Spring Boot testing features and JUnit. This annotation is required every time we use any of the Spring Boot test features in our JUnit tests.

The @SpringBooTtest will enable the full context in the application, and any Spring container-managed Bean can be injected into the test, such as the Service component AddServiceImpl above being injected into addService.

The @test annotation is a Junit annotation indicating that the method is a Test method.

AssertEquals are assertions provided by Junit to determine whether the output of a program is as expected. Similar assertions include:

  • assertTrue
  • assertFalse
  • assertNotEquals
  • assertArrayEquals
  • assertNull
  • assertNotNull
  • assertSame
  • assertNotSame

The meaning is as literal as it is needed

Annotations for Spring Boot tests

Comments on test classes fall into several categories:

  • @RunWith(SpringRunner.class)
  • @ @ xxxxTest SpringBootTest, etc
  • @ AutoConfigureXXXX etc.

RunWith(Springrunner.class), as described earlier, provides a bridge between The Spring Boot test features and JUnit

@ @ xxxxTest SpringBootTest, etc

All @xxxTest annotations are annotated by @bootstrapWith. They start the ApplicationContext and are entry points for testing. All test classes must declare an @xxTest annotation.

  • @SpringBooTtest automatically detects and loads the configuration in @SpringBootApplication or @SpringBootConfiguration. The default Web environment is MOCK and does not listen to the task port
  • The @dataredistest test operates on Redis, automatically scanning classes described by @redishash and configuring Spring DataRedis libraries
  • The @DatajPatest test is based on JPA database operations and provides TestEntityManager as an alternative to JPA EntityManager
  • DataJdbcTest Tests database operations based on Spring Data JDBC
  • JsonTest tests the serialization and deserialization of JSON
  • WebMvcTest tests the Controllers in Spring MVC
  • WebFluxTest tests the Controllers in Spring WebFlux
  • RestClientTest Tests operations on REST clients
  • DataLdapTest Tests the operation on LDAP
  • @datamongoTest Tests the operation on MongoDB
  • DataNeo4jTest Tests the operation with Neo4j

In general, you can use @SpringBooTtest to scan all Spring configurations in the project. For others, you can add corresponding configurations by using the following AutoConfigurexxx annotations

@ AutoConfigureXXXX etc.

  • AutoConfigureJdbc Automatically configures JDBC
  • @autoconfigurecache Automatically configures the cache
  • AutoConfigureDataLdap Automatically configures LDAP
  • @autoconfigurejson Automatically configures JSON
  • @autoconfigurejsontesters automatically configures JsonTester
  • AutoConfigureDataJpa Automatically configures JPA
  • @ AutoConfigureTestEntityManager TestEntityManager automatic configuration
  • @autoConfigurerestDocs Configurs RestDocs automatically
  • @ AutoConfigureMockRestServiceServer MockRestServiceServer automatic configuration
  • AutoConfigureWebClient Automatically configures WebClient
  • @autoconfigureWebFlux Automatically configures WebFlux
  • @ AutoConfigureWebTestClient WebTestClient automatic configuration
  • @autoconfiguremockMVC Automatically configures MockMvc
  • AutoConfigureWebMvc Automatically configures WebMvc
  • @autoconfigureDataneo4j Automatically configures Neo4j
  • @autoconfigureDataredis Automatically configures Redis
  • @autoconfigureJooq Automatically configures Jooq
  • @ AutoConfigureTestDatabase automatically configure the Test Database, you can use the memory Database

These annotations can be used with @xxxTest to enable functionality that is not automatically configured in @xxxTest. Such as @ SpringBootTest and @ AutoConfigureMockMvc after combination, can inject org. Springframework. Test. Web. Servlet. MockMvc

summary

Spring Boot Test provides us with a convenient unit Test tool, which can easily get the beans we configure in the program. In addition, it also provides Mock function and WebMvc Test, MockMvc and other functions. With JsonPath Expressions, you can easily unit test the Collector layer and service layer, which we’ll cover next time.