学了springboot之后,发现里面的单元测试还不太好用,甚至不会用。
原因很简单,通常在启动一个单元测试之后,没有conttetxt上下文,以及各个bean,则导致想要调用的方法都不能调用,感觉很困扰。
另外,各处的说法好像很乱,因为spring有多种版本,springboot有多种版本,单元测试框架有多个以及多个版本。所以更觉得乱七八糟。
今天就来整理一下,实现基于一般的简单的springboot项目的单元测试写法。
如下图
然后,建立一个最简单的springboot项目。
就是随便带一个RestController方法,可以调用一下的那种。
如下图这样简陋的:
类似上面这个简单的东西。
也许值得一提的是,springboot的版本号。
3. 设法实现单元测试 3.1 直接上代码org.springframework.boot spring-boot-starter-web2.5.3 test //scope写不写都行
直接上代码:
代码如下:
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;
//@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等。
项目地址: 一个最简单的springboot单元测试demo



