【Spring】Junit加载Spring容器作单元测试
如果我们需要对我们的Service方法作单元测试,恰好又是用Spring作为IOC容器的,我们可以这么配置Junit加载Spring容器,方便做单元测试。
> 基本的搭建
(1)引入所需的包
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>3.2.10.RELEASE</version> </dependency>
(2)写测试类
测试类中要设置加载哪些Spring的配置(我这里是“/config/application*.xml”),然后就可以注入容器中的bean了。
package com.nicchagil.mybatis3spring3intg.junit; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.nicchagil.mybatis3spring3intg.bean.User; import com.nicchagil.mybatis3spring3intg.service.UserService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"/config/application*.xml"}) public class JunitTest { @Autowired private UserService userService; @Test public void c1() { List<User> userList = userService.query(new User()); System.out.println(userList); } }
> 常见的用法
常用的方式是将加载配置的部分公用出来:
package com.nicchagil.mybatis3spring3intg.junit; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"/config/application*.xml"}) public class BaseJunit { }
然后需要的各个测试类继承公用类:
package com.nicchagil.mybatis3spring3intg.junit; import java.util.List; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.nicchagil.mybatis3spring3intg.bean.User; import com.nicchagil.mybatis3spring3intg.service.UserService; public class UserServiceTest extends BaseJunit { @Autowired private UserService userService; @Test public void c1() { List<User> userList = userService.query(new User()); System.out.println(userList); } }
作者:Nick Huang 博客:http://www.cnblogs.com/nick-huang/
本博客为学习、笔记之用,以笔记形式记录学习的知识与感悟。学习过程中可能参考各种资料,如觉文中表述过分引用,请务必告知,以便迅速处理。如有错漏,不吝赐教。
如果本文对您有用,点赞或评论哦;如果您喜欢我的文章,请点击关注我哦~
本博客为学习、笔记之用,以笔记形式记录学习的知识与感悟。学习过程中可能参考各种资料,如觉文中表述过分引用,请务必告知,以便迅速处理。如有错漏,不吝赐教。
如果本文对您有用,点赞或评论哦;如果您喜欢我的文章,请点击关注我哦~
标签:
Spring framework
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用