SpringBoot之添加单元测试
2023-03-14 10:23:16 时间
在SpringBoot里添加单元测试是非常简单的一件事,我们只需要添加SpringBoot单元测试的依赖jar,然后再添加两个注解就可搞定了。
首先我们来添加单元测试所需要的jar
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency>接着我们写了一个单元测试的demo
package com.zkn.learnspringboot.service.test; import com.zkn.learnspringboot.FirstExample; import com.zkn.learnspringboot.service.PersonService; 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; /** * Created by wb-zhangkenan on 2016/11/18. */ @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = FirstExample.class) public class TestService extends BaseTestService{ @Autowired private PersonService personService; @Test public void testSys() { System.out.println(personService.getPersonDomain().toString()); } }然后我们run一下,一个单元测试就搞定了。
另外:@RunWith和@SprintBootTest这两个注解上都有@Inherited这个注解,所以我们可以定义一个单元测的父类,然后所有的单元测试类继承这个父类就行了。如下所示:
package com.zkn.learnspringboot.service.test; import com.zkn.learnspringboot.FirstExample; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Created by zkn on 2016/11/20. */ @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = FirstExample.class) public class BaseTestService { }
package com.zkn.learnspringboot.service.test; import com.zkn.learnspringboot.service.PersonService; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; /** * Created by wb-zhangkenan on 2016/11/18. */ public class TestService extends BaseTestService{ @Autowired private PersonService personService; @Test public void testSys() { System.out.println(personService.getPersonDomain().toString()); } }如果你用的SpringBoot是1.4.0之前的话,所用的注解稍有不同。你需要把@SpringBootTest注解换成@SpringApplicationConfiguration和@WebAppConfiguration。
相关文章
- Java要抛弃祖宗的基业,Java程序员危险了!
- 十大 Java 语言特性
- JVM 三色标记算法,原来是这么回事!
- 聊聊 Spring 事务控制策略以及 @Transactional 失效问题避坑
- 写给 Java 程序员的前端 Promise 教程
- 写给 Java 程序员的前端 Promise 教程,你学会了吗?
- Java 中为什么不全部使用 Static 方法?
- Java 池化技术你了解多少?
- Java 服务 Docker 容器化优秀实践
- Spring Boot + EasyExcel导入导出,简直太好用了!
- 我们一起聊聊 Java 内存泄漏
- CentOS 下安装 Docker 极简教程
- JDK 19 功能集冻结:Java 19 只有七个新特性
- 关于 CMS 垃圾回收器,你真的懂了吗?
- 为什么会有这么多编程语言?
- 改善Java代码的八个建议
- 接口流量突增,如何做好性能优化?
- Java 以编程方式创建JAR文件
- POJO、Java Bean是如何定义的
- Spring 的 Bean 明明设置了 Scope 为 Prototype,为什么还是只能获取到单例对象?