springboot + Gradle test时报错:No tests found for given includes:xxxx
- 1. 问题描述
- 2. 问题解决
- 配置测试运行器
- 3. Spring boot junit
安装了idea新版本之后是自带了junit 测试的。
项目是springboot 用gradle构建的项目
1. 问题描述
@Test
public void test() throws Exception {
这里我添加了个测试点击如下 进行测试
报错如下:
2. 问题解决
配置测试运行器
- 在Gradle工具窗口中,打开 Gradle设置页面。
- 在“ 运行测试使用”列表中,为选定的Gradle项目选择以下测试运行器选项之一:
- Gradle:IntelliJ IDEA使用Gradle作为默认测试运行器。结果,在持续集成(CI)服务器上获得相同的测试结果。此外,在命令行中运行的测试将始终在IDE中运行。
- IntelliJ IDEA:选择此选项可将测试过程委派给IntelliJ IDEA。在这种情况下,IntelliJ IDEA使用 JUnit 测试运行器,并且由于增量编译,测试运行得更快。
选择每个测试:选择此选项可配置每个测试专门使用哪个测试运行器(Gradle或IntelliJ IDEA)。
这里要选择IntelliJ IDEA
如下图:
确定后,再执行上述 成功!
3. Spring boot junit
- 测试的基类(后续测试类只需要集成该类即可,免去添加注解)
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringRunner.class)
@SpringBootTest
//由于是Web项目,Junit需要模拟ServletContext,
//因此需要给测试类加上@WebAppConfiguration。
@WebAppConfiguration
public class BaseTest {
@Before
public void init() {
System.out.println("开始测试-----------------");
}
@After
public void after() {
System.out.println("测试结束-----------------");
}
}
- 测试类
public class ServiceTest extends BaseTest{
@Test
public void test(){
}
}
- 运行
在上述配置好以后,就可运行测试了。有两种方式,
- 方式一:测试类 不继承上述BaseTest ,仅在方法上添加@Test注解后运行
这种方式就相当于java se的运行(单纯的运行方法,不构造spring容器)。 - 方式二: 测试类 继承上述BaseTest ,并在方法上添加@Test注解后运行 这种方式相当于运行java web ,启动了spring容器,但速度比较,因为要加载spring容器。
以方式二启动在控制台会有如下输出:
- 选择哪一种?
如果不涉及bean 的注入 (@Autowired)这种的,单纯的方法测试,建议使用方式一。(不启动spring容器),这样会省下很多时间。
所以根据需要可灵活选择。