【Java】在SpringBoot项目中使用单元测试

1.引入单元测试依赖

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

2.使用
1)在测试类上添加如下注解

1
2
@RunWith(SpringRunner.class)
@SpringBootTest

2)在测试方法中添加如下注解

1
@Test

实例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.example.demo.test;

import com.example.demo.service.IUserService;
import com.example.demo.service.impl.UserServiceImpl01;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;

/**
* @author chenhy
* @date 2021/4/11
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserTest {

// @Autowired
// @Qualifier("userServiceImpl02")
@Resource(type = UserServiceImpl01.class)
IUserService userService;

@Test
public void test() {
userService.say();
}
}

注意,包的引入千万别弄错了。