【笔记】SpringBoot项目整合JUnit

前言

SpringBoot项目整合JUnit学习笔记

添加依赖

pom.xml
1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

单元测试

  • 在测试类上用@SpringBootTest注解标注

@SpringBootTest:如果测试类放在了与@SpringBootApplication标注的类同级或子级,那么可以省略classes参数
@SpringBootTest(classes = "Application.class"):如果测试类没有放在与@SpringBootApplication标注的类同级或子级,那么需要添加classes参数指定@SpringBootApplication标注的类

src/test/java/com/server/UserServiceTests.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.server;

import com.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class UserServiceTests {

@Autowired
private UserService userService;

@Test
public void test() {

}

}

完成

参考文献

哔哩哔哩——黑马程序员