Introduction to the

Spring Boot Test is a reencapsulation on top of Spring Test, with sliced tests and enhanced mock capabilities.

In general, Spring Boot Test supports three types of tests

category describe Notes involved
Unit testing In Web projects, generally method-oriented, testing costs are high when writing common business code @Test
Slicing test It is generally oriented towards hard-to-test boundary functions, between unit testing and functional testing @ ExtendWith (SpringExtension. Class), @ WebMvcTest, etc
A functional test Typically for a complete business function, you can also use the mock capability in aspect testing @ ExtendWith (SpringExtension. Class), @ SpringBootTest, etc

Rely on

To use Spring Boot Test, you need to import the spring-boot-starter-test dependency package. Starting with Spring Boot 2.2.0, JUnit 5 replaces JUnit 4 as the default library for Spring Boot Test unit tests. Of course, JUnit 5 is compatible with JUnit 4. If you have migrated your tests to JUnit 5, you should exclude support for JUnit 4, as shown below

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

After spring-boot-starter-test is introduced, the following common test dependencies are also introduced

The name of the Introduction to the
JUnit Java unit testing framework
Spring Test & Spring Boot Test Spring’s testing support
AssertJ Assertion library, which provides a streaming assertion mode
Hamcrest Matching object library
Mockito A mock framework that allows you to create mock objects by type and also supports assertions for mock invocation procedures
JSONassert JSON assertion library
JsonPath XPATH functionality is provided for JSON

Application scenario of Spring Boot Test

Dependency injection is one of the main advantages of Spring Boot, but most unit tests of Spring Boot projects use mock objects rather than actual dependencies, so unit tests rarely use Spring Boot Test functionality.

The main application scenarios of Spring Boot Test are Test types that are larger than unit tests, such as slice tests, functional tests, and so on.

Introduce Spring features into the test class

SpringBoot provides the @SpringBooTtest annotation when you need SpringBoot features to perform functional tests on a SpringBoot project, The @SpringbooTtest replaces the @ContextConfiguration annotation in Spring-test to load the ApplicationContext and start the Spring container

It can be used as an alternative to the @ContextConfiguration annotation of the standard Spring-test,

If you are using JUnit 4, in addition to importing @SpringbooTtest you also need to include @runwith (springrunner.class) in your tests to integrate JUnit and Spring. If you are using JUnit 5, No need to add @runwith (springrunner.class), As of SpringBoot 2.2.0, @Springboottest and @xxxtest annotations include an equivalent annotation for @runwith (springrunner.class) @ ExtendWith (SpringExtension. Class).

With The introduction of Spring Boot in JUnit 4, note the package from which each annotation comes

import org.junit.Test;
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 MyTest {

    @Test
    public void test(a) {}}Copy the code

Spring Boot was introduced in JUnit 5

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class MyTest {

    @Test
    public void test(a) {}}Copy the code

@SpringBootTestIt’s included in the annotations@RunWith(SpringRunner.class)Equivalent annotations@ExtendWith(SpringExtension.class).

A functional test

After using @SpringbooTtest, Spring will load all managed beans, which is basically equivalent to starting the entire service. Since @SpringbooTtest is heavy, it is usually used for functional testing

You can specify the environment for the Web by setting the webEnvironment property of @SpringbooTtest, which has four enumerated values

The name of the instructions
MOCK MOCK is the default value, which provides a MOCK environment that can be used with@AutoConfigureMockMvc@AutoConfigureWebTestClientUsed in conjunction, enable Mock related functionality. Note that the embedded service (servlet container) is not actually started and does not listen on the Web service port.
RANDOM_PORT Start a real Web service and listen on a random port.
DEFINED_PORT Start a real Web service, listening on a defined port (read from application.properties).
NONE Launch a non-Web ApplicationContext that provides neither a mock environment nor a real Web service.
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.MOCK;

@SpringBootTest(webEnvironment = MOCK)
public class MyTest {

    @Test
    public void test(a) {}}Copy the code

If there are no Web-related dependencies in the classpath of the current service, @SpringBooTtest will launch a non-Web ApplicationContext, in which case the specified webEnvironment will lose its effect

Slicing test

Slice testing, called “Slice” of your Application in the official documentation, is actually a name for some specific components. Slice here is not a separate class (after all, regular classes only require junit-based unit tests), but rather a range between unit testing and functional testing.

Slice refers to some modules that can be executed in a specific environment, such as Controller in MVC, JDBC database access, Redis client, etc. Most of these modules cannot be run independently from a specific environment. If Spring does not provide test support for this, Developers can only launch full services to test these modules, which is inconvenient in complex systems, so Spring provides testing support for these modules, giving developers the ability to test them individually.

Enable test support for specific modules with @xxxtest. Spring loads only relevant beans and does not load irrelevant content.

Spring Boot section test support modules and corresponding annotations are

annotations role
@DataRedisTest The test forRedisOperation, automatic scanning by@RedisHashDescribes the class and configures itSpring Data RedisIn the library
@DataJpaTest Based on the testJPAThe database operation is also providedTestEntityManageralternativeJPAEntityManager
@DataJdbcTest Based on the testSpring Data JDBCDatabase operation of
@JsonTest testJSONSerialization and deserialization of
@WebMvcTest testSpring MVCIn thecontrollers
@WebFluxTest testSpring WebFluxIn thecontrollers
@RestClientTest The test forRESTClient-side operations
@DataLdapTest The test forLDAPThe operation of the
@DataMongoTest The test forMongoDBThe operation of the
@DataNeo4jTest The test forNeo4jThe operation of the

All @*Test annotations are annotated by @bootstrapWith. They start the ApplicationContext, which is the entry point to the Test. All tangent Test classes must declare an @*Test annotation.

Annotations other than @Springboottest are for cross-section testing, and they import automatic configurations by default. Click on the official Docs for details.

Spring Boot Test Common comments

There are many annotations in Spring Boot Test, which are mainly classified as follows

type annotations instructions
Configuration type @TestConfiguration Provides some configuration entry for testing
The mock type @MockBean Providing mock support
Launch test type @SpringBootTest@*Test An annotation ending with Test has the ability to load the applicationContext
Automatic configuration type @AutoConfigure* Annotations that begin with AutoConfigure have the ability to load test support features.

Configuration type annotations

annotations role Use in practice
@TestComponent The annotation is another kind@Component, semantically used to specify that a Bean is specifically for testing. This annotation is used infrequently when the test code and the formal mix are not loaded with beans described by the annotation.
@TestConfiguration This annotation is another one@TestComponent, which is used to supplement additional beans or overwrite existing beans Make the configuration more flexible without modifying the formal code
@TypeExcludeFilters Used to rule out@TestConfiguration@TestComponent It is suitable for scenarios where test code and formal code are mixed and used infrequently
@OverrideAutoConfiguration Can be used to overlay@EnableAutoConfiguration, andImportAutoConfigurationUsed in combination to limit the autoconfiguration classes loaded Provides the ability to modify the configuration auto-configuration class without modifying the formal code
@PropertyMapping define@AutoConfigure*The name of the variable used in the annotation, for example in@AutoConfigureMockMvcKnown as defined in the spring. Test. Mockmvc. Webclient. Variables enabled Generally not used

Using @SpringBootApplication to start tests or production code, beans described by @testComponent are automatically excluded. If not, you need to add TypeExcludeFilter to @SpringBootApplication.

Mock type annotations

annotations role
@MockBean Used for mock specified classes or annotated properties
@MockBeans make@MockBeanMultiple occurrences of the same type or attribute are supported
@SpyBean Used for classes or annotated properties specified by spy
@SpyBeans make@SpyBeansMultiple occurrences of the same type or attribute are supported

The @MockBean and @SpyBean annotations already exist in the Mockito framework and function essentially the same. Spring Boot Test in turn defines a duplicate annotation to make mockBeans and SpyBeans managed by the ApplicationContext for easy use.

MockBean and SpyBean are very similar in function, and both simulate the behavior of methods. The difference is that a MockBean is a brand new object and has no relationship to a formal object; SpyBean is closely tied to the formal object and can simulate some methods of the formal object. Methods that are not simulated can still run the formal code.

Auto-configure type annotations

annotations role
@AutoConfigureJdbc Automatic JDBC configuration
@AutoConfigureCache Automatic configuration cache
@AutoConfigureDataLdap Configuring LDAP automatically
@AutoConfigureJson Automatic configuration JSON
@AutoConfigureJsonTesters Automatically configure JsonTester
@AutoConfigureDataJpa Automatically configure JPA
@AutoConfigureTestEntityManager Automatically configure TestEntityManager
@AutoConfigureRestDocs Automatically configure Rest Docs
@AutoConfigureMockRestServiceServer Automatically configure MockRestServiceServer
@AutoConfigureWebClient Automatically configure WebClient
@AutoConfigureWebFlux Automatically configure WebFlux
@AutoConfigureWebTestClient Automatically configure WebTestClient
@AutoConfigureMockMvc Automatically configure MockMvc
@AutoConfigureWebMvc Automatically configure WebMvc
@AutoConfigureDataNeo4j Automatically configure Neo4j
@AutoConfigureDataRedis Automatically configure Redis
@AutoConfigureJooq Automatically configure Jooq
@AutoConfigureTestDatabase Test Database is automatically configured to use in-memory databases

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

Automatic Configuration type can be used in two ways:

  1. In functional testing (i.e@SpringBootTest) to display add.
  2. Generally used implicitly in slice testing, e.g@WebMvcTestWhen annotated, implicitly added@AutoConfigureCache,@AutoConfigureWebMvc,@AutoConfigureMockMvc.

The implementation principle is slightly different from the @\*AutoConfiguration implementation in spring-boot-Autoconfigure. The @AutoConfigure\* in the Test package uses the DeterminableImports interface as the identification entry for the specified code and ImportAutoConfiguration as the configuration entry. Read configuration files from the Spring. factories under the Test package. Each @autoconfigure \* can contain multiple @\* autoconfigurations of spring Boot

Start an annotation for the test type

All @*Test annotations are annotated by @bootstrapWith. They start the ApplicationContext, which is the entry point to Spring aspect tests. All Spring aspect Test classes must declare an @*Test annotation.

annotations role
@SpringBootTest Automatic detection and loading@SpringBootApplication@SpringBootConfigurationConfiguration, defaultwebThe environment forMOCK, does not listen on any ports
@DataRedisTest The test forRedisOperation, automatic scanning by@RedisHashDescribes the class and configures itSpring Data RedisIn the library
@DataJpaTest Based on the testJPAThe database operation is also providedTestEntityManageralternativeJPAEntityManager
@DataJdbcTest Based on the testSpring Data JDBCDatabase operation of
@JsonTest testJSONSerialization and deserialization of
@WebMvcTest testSpring MVCIn thecontrollers
@WebFluxTest testSpring WebFluxIn thecontrollers
@RestClientTest The test forRESTClient-side operations
@DataLdapTest The test forLDAPThe operation of the
@DataMongoTest The test forMongoDBThe operation of the
@DataNeo4jTest The test forNeo4jThe operation of the

Annotations other than @Springboottest are for cross-section testing, and they import automatic configurations by default. Click on the official Docs for details.

In general, it is recommended to use annotations from @Springboottest rather than other slice tests, simple and effective. If a change involves only specific slices, consider using slice tests.

The most commonly used of these annotations is @Springboottest, which contains the following configuration items:

The name of the configuration instructions
value Specifying configuration properties
properties Specifies a configuration attribute, which has the same meaning as value
classes Specifies the configuration class, equivalent to@ContextConfigurationClass, if not specified, looks for nested@ConfigurationClass, and then return toSpringBootConfigurationSearch configuration
webEnvironment Specify the Web environment. Possible values are:MOCK,RANDOM_PORT,DEFINED_PORT,NONE

WebEnvironment:

An optional value instructions
MOCK This value is the default and provides a mock environment where the embedded service (servlet container) is not actually started and does not listen on the Web port.
RANDOM_PORT Start a real Web service and listen on a random port.
DEFINED_PORT Start a real Web service, listening on a defined port (read from the configuration).
NONE Launch a non-Web ApplicationContext that provides neither a mock environment nor a real Web service.