1. 背景
学了springboot之后,发现里面的单元测试还不太好用,甚至不会用。
原因很简单,通常在启动一个单元测试之后,没有conttetxt上下文,以及各个bean,则导致想要调用的方法都不能调用,感觉很困扰。
另外,各处的说法好像很乱,因为spring有多种版本,springboot有多种版本,单元测试框架有多个以及多个版本。所以更觉得乱七八糟。
今天就来整理一下,实现基于一般的简单的springboot项目的单元测试写法。
2. 实践
2.1 先建立一个空白的最简单的springboot项目
如下图
然后,建立一个最简单的springboot项目。
就是随便带一个RestController
方法,可以调用一下的那种。
如下图这样简陋的:
类似上面这个简单的东西。
也许值得一提的是,springboot的版本号。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.5.3</version>
<scope>test</scope> //scope写不写都行
</dependency>
3. 设法实现单元测试
3.1 直接上代码
直接上代码:
代码如下:
import org.example.demo.DemoStarter;
import org.example.demo.service.ITestService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author zs
* @date 2021/10/15 16:24
* @Email:
* @desc:两个RunWith的class,属于继承关系,随便写哪个都一样。
*/
//@RunWith(SpringRunner.class)
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = DemoStarter.class)
public class Test1 {
@Autowired
private ITestService test1Service;
@Test
public void aaa() {
String s = test1Service.serviceMethod1();
System.out.println(s);
Assert.assertTrue(!s.isEmpty());
}
}
代码中的关键点:@RunWith(SpringJUnit4ClassRunner.class)
,以及 @SpringBootTest(classes = DemoStarter.class)
, 尤其是后面的这个classes = DemoStarter.class
,指向启动类。
然后才可以获取到对应的上下文,各个bean等。
4. 测试成功。
项目地址: 一个最简单的springboot单元测试demo