Spring Boot中进行Junit测试
2024-09-07 15:56:27
Spring Boot新版本默认使用Junit5,pom依赖为:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
同时,测试类的Demo如下,其中@SpringBootTest表示将该类作为Spring的测试类,加载到spring容器中,必不可少。
import static org.junit.jupiter.api.Assertions.assertEquals; import example.util.Calculator; import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class MyFirstJUnitJupiterTests { private final Calculator calculator = new Calculator(); @Test
void addition() {
assertEquals(2, calculator.add(1, 1));
} }
如果项目中要使用旧版的Junit4,那么在pom文件中要删除掉“<exclusions>”这个对旧版本的支持,同时导入Junit4的相关依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
在测试类中,不要忘了添加@Runwith(SpringRunner.class)注解,有时候@Test的导入的包也有影响,需要注意
文档:
Junit5:https://junit.org/junit5/docs/current/user-guide/#writing-tests
最新文章
- SpringMVC参数自动绑定
- Spring 学习笔记 3. 尚硅谷_佟刚_Spring_配置 Bean
- hdu 1863 - 畅通工程(MST)
- HTML学习笔记——块级标签、行级标签、图片标签
- css/js(工作中遇到的问题)
- CocoaPods Podfile 文件写法有讲究
- 08.C# System.Nulable<;T>;和空引用操作符(四章4.2-4.4)
- Java中单例设计模式总结
- Excel图表-";DNA";图
- 用CNN对CIFAR10进行分类(pytorch)
- SuperDiamond在JAVA项目中的三种应用方法实践总结
- JS判断元素 动画是否执行完成
- 网页全屏,modal 弹框无法显示的问题
- Sharding模式
- nginx 操作笔记
- Android-json解析:原生JSONObject+JSONArray的使用【转】
- ZW云推客即将登场
- bootstrap 4 panels已被card替换
- JAVA多线程提高三:线程范围内共享变量&;ThreadLocal
- Python+Selenium框架设计篇之-什么是POM