Spring Junit测试(非web,即不包含Controller测试)

使用Spring-Test对Spring框架进行单元测试

配置过程:

lib加入导入spring-test.jar和junit包

或者使用Maven依赖:

 1  <dependency>  
 2             <groupId>junit</groupId>  
 3             <artifactId>junit</artifactId>  
 4             <version>4.9</version>  
 5             <scope>test</scope>  
 6 </dependency>   
 7 <dependency>  
 8             <groupId>org.springframework</groupId>  
 9             <artifactId>spring-test</artifactId>  
10             <version> 4.1.3.RELEASE</version>  
11             <scope>provided</scope>  
12 </dependency>  

 

方式一:直接测试

 1 @RunWith(SpringJUnit4ClassRunner.class) //使用junit4进行测试  
 2 @ContextConfiguration(locations={"classpath:applicationContext.xml"}) //加载配置文件    
 3 //测试数据库时候加上事务控制(前提在配置文件中配置事务管理器)
4 @TransactionConfiguration(transactionManager="transactionManager",defaultRollback=true)配置事务的回滚,对数据库的增删改都会回滚,便于测试用例的循环利用
  @Transactional
5 public class MyJunit4Test{ 6 7 @Resource 8 public MyService service; 9 10 @Test 11 public void testXXX() { 12 boolean reslut = service.exists(); 13 Assert.assertEquals(true, reslut); 14 } 15 }

方式二:创建测试模板类,要测试的类继承它即可

编写SpringTestBase基础类,加载所需xml文件:

 1 @ContextConfiguration(locations = { "classpath:Application-Redis.xml" })
 2 @RunWith(SpringJUnit4ClassRunner.class)
 3 public class SpringTestBase extends AbstractJUnit4SpringContextTests {
 4  }
 5 
 6 
 7 public class TestRedisCacheDaoImpl extends SpringTestBase {
 8 
 9     @Autowired
10     public RedisCacheDaoImpl redisCacheDaoImpl;
11 
12     @Test
13     public void testPing() {
14         boolean reslut = redisCacheDaoImpl.ping();
15         Assert.assertEquals(true, reslut);
16     }
17 
18 }

 

 
posted @ 2018-04-11 21:51  染红の街道  阅读(354)  评论(0编辑  收藏  举报