junit单元测试使用H2内存数据库

    首先导入H2内存数据库,Junit4单元测试依赖。

<dependency>
	<groupId>com.h2database</groupId>
	<artifactId>h2</artifactId>
	<version>1.4.185</version>
	<scope>test</scope>
</dependency>
<dependency>
	<groupId>junit</groupId>
	<artifactId>junit</artifactId>
	<version>4.11</version>
	<scope>test</scope>
</dependency

    其次使用H2数据源模拟Oracle

@Component
@Profile("testOne") // 指定单元测试活动所匹配的数据源
public class DataSourceConfig4Test {

    @Bean(name="dataSourceUtils") // 要和模拟的数据源名称相对应
    DataSource dataSourceUtils() throws SQLException {
        return new EmbeddedDatabaseBuilder()
                .setType(EmbeddedDatabaseType.H2)
                .addScript("classpath:/H2_TYPE.sql")
                .addScript("classpath:/INIT_TABLE.sql")
                .addScript("classpath:/H2_FUNCTION.sql")
                .addScript("classpath:/INIT_DATA.sql")   
                .build();
    }
    
}

    H2_TYPE.sql (设置H2所模拟的数据库)

SET MODE Oracle;

    INIT_TABLE.sql (单元测试需要的数据库表初始化)

CREATE TABLE TEST
(
    ID      NUMBER(38,0) PRIMARY KEY NOT NULL, 
    PARAM1  VARCHAR2(6) NOT NULL,
    PARAM2 VARCHAR2(6) NOT NULL,
	PARAM3 VARCHAR2(1) NOT NULL,
	PARAM4 VARCHAR2(50) NOT NULL
);

    H2_FUNCTION.sql (不需要特殊方法时,此不可忽略)

CREATE ALIAS TO_DATE FOR "com.mvn.task.one.Function.toDate";

    INIT_DATA.sql (初始化测试数据)

INSERT INTO TEST(ID,PARAM1,PARAM2,PARAM3,PARAM4)
VALUES(100,'TEST1','TEST2','2','JKL');

    至此H2部分准备完毕,下面来写个Junit4的单元测试类例子

@ActiveProfiles("testOne") // 需要和H2模拟的数据源对应上
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:testspring/applicationContext-test-one.xml")
public class oneTest {

	@Autowired
	private ITestService iTestService;
	
	@Test
	public void testBengin(){
	    Test model = iSubcService.findTest("TEST1", "TEST2");
	    Assert.assertNotNull(model);
	}

}

 到此H2和Junit单元测试完成,另外一个数据源单元测试重复以上步骤即可,如有疑问请留言,欢迎拍砖,如有不同意见或更好的解决方案,也请留言~

猜你喜欢

转载自zliguo.iteye.com/blog/2255875