使用Maven + Hibernate + SpringTest框架进行单元测试Demo

阅读更多

使用Maven + Hibernate + SpringTest框架进行单元测试Demo

 

之前有同事研究内嵌DB以便提供单元测试所需的数据环境,无果,毕竟难以完全实现各种类型DB的独有特性了。我们采用Mock的方式,进行依赖对象构建。由于系统没有基于依赖注入的进行建构,编写UnitTest很容易成了搭建复杂繁琐的系统环境,背离了“单元”的初衷。我在考虑,采用SpingTest框架为单元测试提供了便利的依赖注入管理设施,使我们从冗余复杂中解放出来。而使用Hibernate对底层持久化进行了屏蔽,很好实现了高层次API单元测试的DB独立性。Maven天生对UnitTest的内建支持,专门搞了个phasetest,如果真的做到面向接口,测试针对接口,自动化测试也不是不可能。

 

于是做了一个简单的Demo如下:

 

Maven管理各种Jar依赖,在这里使用了HsqlDB作为内存DB

 

Maven POM文件


  4.0.0
  floyd.welsney
  orm-demo
  0.0.1-SNAPSHOT
  jar

  
    UTF-8
  
  
  
    
      jboss-hibernate
      https://repository.jboss.org/nexus/content/groups/public/
    
  
  
  
    
      
        org.apache.maven.plugins
        maven-compiler-plugin
        2.3.2
        
          1.6
          1.6
        
      
    
  
  
  
    
      junit
      junit
      4.10
      test
    
    
    
      org.hsqldb
      hsqldb
      2.2.4
      test
    

    
      org.hibernate
      hibernate
      3.2.6.GA
    
    
    
      log4j
      log4j
      1.2.16
    
    
    
      org.springframework
      spring-test
      3.0.6.RELEASE
    

    
      org.springframework
      spring-context
      3.0.6.RELEASE
    
    
    
      org.springframework
      spring-orm
      3.0.6.RELEASE
    

  

 

创建Spring管理的上下文

 

Spring配置文件


		
		
		
		
    
    
    
    	
    
	
	
		
		
			
				hibernate.dialect=org.hibernate.dialect.HSQLDialect
				hibernate.show_sql=true
				hibernate.use_sql_comments=true
				hibernate.format_sql=true
			
		
		
			
		    	
		    
		
	

	
			
	
 

下面是Java Code

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class BaseSpringManagedContextJunitTest {

	protected final Logger logger = LogManager.getLogger(this.getClass());
	
	@Autowired
	protected SimpleJdbcTemplate simpleJdbcTemplate;
	
	@Autowired
	protected HibernateTemplate hibernateTemplate;
	
	protected final void execSqlScript(String scriptPath) {
		Resource resource = new ClassPathResource(scriptPath);
		SimpleJdbcTestUtils.executeSqlScript(simpleJdbcTemplate, resource, false);
	}
	
	@Before
	public void setUp() {
		execSqlScript("floyd/welsney/test/sql/schema.sql");
		execSqlScript("floyd/welsney/test/sql/data.sql");
		logger.debug("hsqldb is setup");
	}
	
	@After
	public void tearDown() {
		execSqlScript("floyd/welsney/test/sql/clear.sql");
		logger.debug("hsqldb is tearDown");
	}

	@Test
	public void testXXXX() {
		logger.debug("Perform unit test");
	}
}
 

说明一下代码,

指定ContextConfiguration的Location来加载Spring管理的上下文环境配置文件。

◎Autowired说明需要注入的外部依赖。

◎Before用来加载全新的DB Schma和相应的数据。

◎After清理DB环境的脏数据,以为下一次test准备。

 

最后执行命令mvn test即可,Eclipse下可以Alt+Shift+X+T运行

你可能感兴趣的:(UnitTest,junit,Spring,单元测试)