Writing unit tests for your application is a good habit. The most popular testing tool in Java development is JUnit, which has become the de facto standard for Java unit testing. The Spring Boot test module not only integrates with the JUnit framework, but also provides a number of utilities and annotations for testing applications.
1. Add dependencies
Introduce spring-boot-starter-test in the pom.xml file
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${version}</version>
<scope>test</scope>
</dependency>
Copy the code
Spring Boot 2.2.x starts with JUnit 5. If you were using JUnit 4, you can run with the older engine provided in JUnit 5, requiring the addition of junit-vintage-engine dependencies.
Spring Boot 2.2.x has been released for a long time, and now the latest stable release is 2.4.x. The old ones will always be replaced, so this article will only use JUnit 5. I believe there are many articles about JUnit 4 on the Internet, and there are also official instructions for use, please find them by yourself.
2. Write unit tests
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class JUnitTest {
@Test
public void test(a) {
// Test the code}}Copy the code
@Springboottest Important parameters
- args
Application parameters such as args = “–app.test=one”
- classes
Spring Boot Application Boot entry class name. If this parameter is not specified, Spring Boot searches for it by default.
- webEnvironment
By default, @Springboottest does not start the server. When testing Web applications, you need to specify this parameter to load the context.
WebEnvironment enumeration value description:
- MOCK
Default, loads the WebApplicationContext and provides a mock Web environment. When this annotation is used, the embedded server is not started.
- RANDOM_PORT
Start the application and listen on a random port.
- DEFINED_PORT
Start the application and listen on a custom port (from application.properties) or use the default port 8080.
- NONE
ApplicationContext uses load, SpringApplication but does not provide any network environment (mock or otherwise).
@Test
Note that the @test annotation for JUnit 5 is in the org.junit.jupiter. API package.
If the application uses Spring MVC and Spring WebFlux, MVC is preferred. To test the WebFlux application, you must set:
@SpringBootTest(properties = "spring.main.web-application-type=reactive")
public class MyWebFluxTests {
}
Copy the code
3. Automatic assembly test
Sometimes we just need to test whether the framework module integration is working properly without loading the entire project. Some annotations in the spring-boot-test-autoconfigure module can be used. The entire framework is “sliced” into individual test modules.
JSON test
Test JSON serialization and deserialization. If it is GSON or JSONB, use the @gsonTester or @jsonBTester annotation.
/ * * *@author Engr-Z
* @since2021/1/18 * /
@JsonTest
public class MyJsonTest {
@Autowired
private JacksonTester<Map> json;
@Test
void testSerialize(a) throws Exception {
Map<String, Object> map = new HashMap<>();
map.put("name"."The Lion Of the Siege.");
map.put("websit"."engr-z.com");
Assertions.assertThat(this.json.write(map)).isEqualToJson("expected.json");
Assertions.assertThat(this.json.write(map)).hasJsonPathStringValue("@.make");
Assertions.assertThat(this.json.write(map)).extractingJsonPathStringValue("@.make")
.isEqualTo("Honda");
}
@Test
void testDeserialize(a) throws Exception {
String content = "{\"name\ :\" Siege lion · zheng \",\"website\ :\"engr-z.com\"}";
Assertions.assertThat(this.json.parse(content));
Assertions.assertThat(this.json.parseObject(content).get("website")).isEqualTo("engr-z.com"); }}Copy the code
Spring MVC test
Test whether the /demo/ Hello interface works properly
/ * * *@author Engr-Z
* @since2021/1/18 * /
@WebMvcTest(DemoController.class)
public class SpringMVCTest {
@Autowired
private MockMvc mvc;
@Test
void test(a) throws Exception {
RequestBuilder builder = MockMvcRequestBuilders.get("/demo/hello");
ResultActions resultActions = mvc.perform(builder);
int status = resultActions.andReturn().getResponse().getStatus();
Assertions.assertEquals(200, status); }}Copy the code
Spring WebFlux test
/ * * *@author Engr-Z
* @since2021/1/18 * /
@WebFluxTest(DemoController.class)
public class SpringWebFluxTest {
@Autowired
private WebTestClient webClient;
@Test
void test(a) throws Exception {
webClient.get().uri("/demo/webflux") .accept(MediaType.TEXT_PLAIN) .exchange() .expectStatus().isOk(); }}Copy the code
The JDBC test
@JdbcTest
@Transactional(propagation = Propagation.NOT_SUPPORTED)
class JdbcTransactionalTests {}Copy the code
Autowaging also supports JPA, Redis, Rest Client and other module tests. See auto-configured Tests for more information
@ MockBean and @ SpyBean
If a service depends on the result of a remote invocation. To keep us from doing unit tests, we can use @MockBean. Here’s an example of official code:
@SpringBootTest
class MyTests {
@MockBean
private RemoteService remoteService;
@Autowired
private Reverser reverser;
@Test
void exampleTest(a) {
// RemoteService has been injected into the reverser bean
BDDMockito.given(this.remoteService.someCall()).willReturn("mock");
String reverse = reverser.reverseSomeCall();
Assertions.assertThat(reverse).isEqualTo("kcom"); }}Copy the code
The difference between @SpyBean and @MockBean is that, for methods that do not specify a mock, spy will call the real method by default, and mock will not execute by default, and mock will return null by default
This article covers only the JUnit unit tests for Spring Boot integration; the use of JUnit will be covered in more detail in a later chapter.
Unless otherwise noted, all of them are written by Sieges. Link to this article: engr-z.com/88.html