Spring Boot provides a wealth of testing functions, mainly composed of the following two modules:
-
spring-boot-test
: Provide testing core functions. -
spring-boot-test-autoconfigure
: Provides automatic configuration of tests.
Spring Boot provides a spring-boot-starter-test
one-stop starter, as shown in the following dependency configuration.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
The test starter dependency not only includes the above two Spring Boot modules, but also includes the Spring Test test module, and others
Third-party test class library, as shown below.
-
JUnit 5: Java's most mainstream unit testing framework.
-
AssertJ: A fast assertion library.
-
Hamcrest: A unit test matching library.
-
Mockito: A Mock testing framework.
-
JSONassert: A JSON assertion library.
-
JsonPath: A JSON XPath library.
More test-related dependencies can be seen in the specific dependency tree, as shown in the figure below.
All of the above are commonly used test libraries provided by Spring Boot. If the above test libraries cannot meet your needs, you can also add any of the above-mentioned libraries.
Basically, JUnit 5 is used now. If the application is still using the unit test cases written in JUnit 4, it can also be run using the Vintage engine of JUnit 5, as shown in the following dependency configuration.
<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>
The dependency needs to be excluded hamcrest-core
because the dependency has changed coordinates and is built into Spring Boot dependency management by default. As shown in the dependency tree above, the latest Hamcrest dependency is already org.hamcrest:hamcrest
coordinates.
Spring Boot provides an @SpringBootTest
annotation that is used on the unit test class to enable unit testing that supports Spring Boot features. If you are using JUnit 4, you need additional annotations on the test class, and then add annotations to the test class @RunWith(SpringRunner. class)
methods @Test
, each @Test
annotation-modified method is a unit test method.
@SpringBootTest
The annotation has one of the most important webEnvironment
environment parameters, which supports the following environment settings:
-
MOCK (default): Load one
Web ApplicationContext
and provide oneMock Web Environment
, but will not start the embedded Web server, and can be used in combination@AutoConfifigureMockMvcor
with@AutoConfifigure-WebTestClient
annotations for Mock testing. -
RANDOM_PORT: load one
WebServerApplicationContext
, and provide a real oneWebEnvironment
, and start the embedded server with a random port. -
DEFINED_PORT: The
RANDOM_PORT
same as, but the difference isDEFINED_PORT
that it runs on the port specified by the application, and the default port is 8080. -
NONE: Load one
ApplicationContext
, but will not serve anyWeb Environment
.
If the annotation is used @SpringBootTest
without any parameters, it defaults to the Mock environment.
real environment test
Specify a real web environment based on a random port in @SpringBootTest
the annotation, and then inject an instance into a class member variable or method parameter TestRestTemplate
to complete the real environment test of the Spring MVC interface.
Here is a test case based on a real environment with random ports:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MvcTest {
@Test
public void getUserTest(@Autowired TestRestTemplate testRestTemplate) {
Map<String, String> multiValueMap = new HashMap<>();
multiValueMap.put("username", "Java 技术栈 ");
Result result = testRestTemplate.getForObject("/user/get?username={username}",
Result.class, multiValueMap);
assertThat(result.getCode()).isEqualTo(0);
assertThat(result.getMsg()).isEqualTo("ok");
}
}
Test the interface under the current application /user/get
, pass in the corresponding user name parameter, and finally check whether the returned result of the interface is consistent with the expectation. The test result is shown in the figure below.
The unit test is passed, as can be seen from the execution log, it starts an embedded Tomcat container to test the real web application environment.
Mock environment test
By using annotations on the class @AutoConfifigureMockMvc
, and then injecting MockMvc instances on the class member variables or method parameters, the Mock test of the Spring MVC interface can be completed.
The following is a test case based on the default Mock environment:
@SpringBootTest
@AutoConfigureMockMvc
class MockMvcTests {
@Test
public void getUserTest(@Autowired MockMvc mvc) throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/user/get?username={username}", "test"))
.andExpect(status().isOk())
.andExpect(content().string("{\"code\":0,\"msg\":\"ok\",\"
data\":\"test\"}"));
}
}
Test the interface under the current application /user/get
, pass in the corresponding user name parameter, and finally check whether the request status is OK (200) and whether the content of the response is as expected. The test result is shown in the figure below.
The unit test is passed. From the execution log, it can be seen that it does not start the real Web environment for testing, but uses the Mock environment for testing.
Mock component testing
Sometimes it may be necessary to simulate some components. For example, some services can only be called after they go online and are not available during the development stage. In this case, Mock simulation testing is required, and various simulation components are provided to complete the test.
Spring Boot provides an @MockBean
annotation that can define Mockito-based Mock tests for Bean components in Spring. It can create a new Bean to cover existing Beans in the Spring environment. It can be used on test classes, member variables, or @Confifiguration
configuration On classes, member variables, mocked beans are automatically reset after each test.
Assume that there is a remote service userService
that cannot be called locally, and now conduct a Mock test, as shown in the following usage example.
@SpringBootTest
class MockBeanTests {
// @Autowired
// private UserService userService;
@MockBean
private UserService userService;
@Test
public void countAllUsers() {
BDDMockito.given(this.userService.countAllUsers()).willReturn(88);
assertThat(this.userService.countAllUsers()).isEqualTo(88);
}
}
The annotation here @MockBean
is used on the UserService variable, indicating that this userService
instance is covered by Mock in the current test case. If there are multiple Beans to be simulated, you can use the @Qualififier
annotation to specify, and then create a mock return through the proxy tool class method provided by Mockito Data, run the test method of the service, and the test will pass only when the simulated data is consistent with the expected result.
Here, BDDMockito
the tool class is used to simulate userService#countAllUsers
the method and let it return the total number of users (88), and finally check whether the return value of the method is as expected. The test result is shown in the figure below.
If the unit test is passed, annotations can also be used @SpyBean
instead of @MockBean
annotations. The difference between the two is:
-
@SpyBean
— If no Mockito proxy method is provided, the real Bean will be called to obtain the data. -
@MockBean
— Whether or not the Mockito proxy method is provided, the Bean of the Mock will be called to obtain the data.
@MockBean
, @SpyBean
Annotations can be applied to both the Mock environment and the real environment. It is only used to simulate and replace the specified Bean in the environment, but it cannot be used to simulate the behavior of the Bean during the refresh of the application context, because when executing the test case The application context has been refreshed, so it is impossible to simulate it. In this case, it is recommended to use @Bean
the method to create a simulation configuration.
Finally: In order to give back to the die-hard fans, I have compiled a complete software testing video learning tutorial for you. If you need it, you can get it for free 【保证100%免费】
加入我的软件测试交流群:110685036免费获取~(同行大佬一起学术交流,每晚都有大佬直播分享技术知识点)
Software testing interview applet
The software test question bank maxed out by millions of people! ! ! Who is who knows! ! ! The most comprehensive quiz mini program on the whole network, you can use your mobile phone to do the quizzes, on the subway or on the bus, roll it up!
The following interview question sections are covered:
1. Basic theory of software testing, 2. web, app, interface function testing, 3. network, 4. database, 5. linux
6. web, app, interface automation, 7. performance testing, 8. programming basics, 9. hr interview questions, 10. open test questions, 11. security testing, 12. computer basics
method of obtaining: