# SpringBoot3教程 - 4 单元测试
在开发项目的时候,需要测试代码是否正确,但是调用 service 或 dao 层的代码,没有 Spring 的上下文环境,无法直接调用。如果编写 controller 接口去调用又很麻烦,所以集成并使用单元测试是很有必要的。
下面演示一下SpringBoot中的单元测试,这样后面测试代码的时候比较方便。
# 1 添加依赖
首先引入 spring-boot-starter-test 单元测试依赖。
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
1
2
3
4
5
6
7
2
3
4
5
6
7
# 2 测试service
# 1 编写service
编写一个 service 类,并编写要测试的方法,后面单元测试的时候,调用这个方法。
UserServiceImpl.java
package com.doubibiji.hellospringboot.service.impl;
import com.doubibiji.hellospringboot.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    /**
     * 测试方法
     */
    public String getUserInfo(String userId) {
        log.info("userId:{}", userId);
        return "doubi";
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
只是为了演示单元测试调用 service 中的方法,方法功能不重要。
编写对应的接口 IUserService.java
package com.doubibiji.hellospringboot.service;
public interface IUserService {
    /**
     * 测试方法
     */
    String getUserInfo(String userId);
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 2 测试service方法
在测试包下创建测试类:

在测试类中添加 @SpringBootTest 注解,直接注入 userService,并在测试方法上添加 @Test 注解,就可以运行测试方法进行运行了。
package com.doubibiji.hellospringboot;
import com.doubibiji.hellospringboot.service.IUserService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class UserServiceTests {
    @Autowired
    private IUserService userService;
    @Test
    void contextLoads() {
        String info = userService.getUserInfo("001");
        System.out.println(info);
        // 还可以对返回结果进行断言,判断是否符合预期效果
        Assertions.assertEquals("niubi", info);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
在测试类中调用方法,还可以对返回的结果进行断言,如果不符合结果,会报错。

