Spring Junit测试(非web,即不包含Controller测试)
2024-09-04 14:28:07
使用Spring-Test对Spring框架进行单元测试
配置过程:
lib加入导入spring-test.jar和junit包
或者使用Maven依赖:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version> 4.1.3.RELEASE</version>
<scope>provided</scope>
</dependency>
方式一:直接测试
@RunWith(SpringJUnit4ClassRunner.class) //使用junit4进行测试
@ContextConfiguration(locations={"classpath:applicationContext.xml"}) //加载配置文件
//测试数据库时候加上事务控制(前提在配置文件中配置事务管理器)
@TransactionConfiguration(transactionManager="transactionManager",defaultRollback=true)配置事务的回滚,对数据库的增删改都会回滚,便于测试用例的循环利用
@Transactional
public class MyJunit4Test{ @Resource
public MyService service; @Test
public void testXXX() {
boolean reslut = service.exists();
Assert.assertEquals(true, reslut);
}
}
方式二:创建测试模板类,要测试的类继承它即可
编写SpringTestBase基础类,加载所需xml文件:
@ContextConfiguration(locations = { "classpath:Application-Redis.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringTestBase extends AbstractJUnit4SpringContextTests {
} public class TestRedisCacheDaoImpl extends SpringTestBase { @Autowired
public RedisCacheDaoImpl redisCacheDaoImpl; @Test
public void testPing() {
boolean reslut = redisCacheDaoImpl.ping();
Assert.assertEquals(true, reslut);
} }
最新文章
- [转]NullPointerException异常
- [Ubuntu][Linux]更改PATH路径
- meteor icons &; splash配置
- 散列表 (Hash table,也叫哈希表)
- [cc150] 硬币问题
- datagrid加下拉列表dropdownlist
- OpenCV之Python学习笔记
- Intellij Idea/Webstorm/Phpstorm
- Java模拟post-get提交
- php 启动过程 - reqeust RSHUTDOWN 过程
- BufferedReaderTest
- 20150605面试汇总--js与java的差别
- 基于Spark环境对比Python和Scala语言利弊
- docker iotop :OSError: Netlink error: No such file or directory
- JAVA内部类_2
- Spring Boot 集成 Spring Security 实现权限认证模块
- LinkedHashMap源码分析及实现LRU
- QT pri 文件的作用
- C#使用 System.Net.Mail发送邮件功能
- pyH支持python3