今天写了一个比较长的流程业务,不想启动web容器进行测试,就本地写了一个Junit的测试类进行单元测试,但是由于使用Spring,Junit在使用的时候需要手动加载容器上下文,比较麻烦,所以干脆直接使用Spring-Test来结合Junit来使用。
废话少说,直接上代码:
1、引入依赖
<!-- Spring Junit Test-->
<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> 3.2.4.RELEASE</version>
<scope>provided</scope>
</dependency>
2、初始化容器
这里有个问题,由于我们公司使用的是jndi来配置数据源,并且有多个数据源,因此,需要本地进行一下jndi的绑定,这里我使用了commons-dbcp来进行相关的绑定
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({
"classpath:conf/spring/aaa.xml"})
public class SpringJunitWeb {
@BeforeClass
public static void initDb(){
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://ip:port/dbName?generateSimpleParameterMetadata=true");
dataSource.setUsername(userName);
dataSource.setPassword(password);
dataSource.setMaxActive(50);
dataSource.setDefaultAutoCommit(false);
BasicDataSource dataSource1 = new BasicDataSource();
dataSource1.setDriverClassName("com.mysql.jdbc.Driver");
dataSource1.setUrl("jdbc:mysql://ip:port/dbName?generateSimpleParameterMetadata=true");
dataSource1.setUsername(userName);
dataSource1.setPassword(password);
dataSource1.setMaxActive(50);
dataSource1.setDefaultAutoCommit(false);
BasicDataSource dataSource2 = new BasicDataSource();
dataSource2.setDriverClassName("com.mysql.jdbc.Driver");
dataSource2.setUrl("jdbc:mysql://ip:port/dbName?generateSimpleParameterMetadata=true");
dataSource2.setUsername(userName);
dataSource2.setPassword(password);
dataSource2.setMaxActive(50);
dataSource2.setDefaultAutoCommit(false);
SimpleNamingContextBuilder sncb = new SimpleNamingContextBuilder();
sncb.bind("java:jboss/jdbc/dataSource",dataSource);
sncb.bind("java:jboss/jdbc/dataSource1",dataSource1);
sncb.bind("java:jboss/jdbc/dataSource2",dataSource2);
try {
sncb.activate();
} catch (NamingException e) {
e.printStackTrace();
}
}
}
3、相关的测试类
@ContextConfiguration(value = "classpath:conf/spring/spring-*.xml")
public class ControllerTest extends SpringJunitWeb {
@Resource
private IBizService bizSevice;
@Test
public void testDoBiz() {
bizSevice.doBiz();
}
}
这里注意的是默认dbcp中的autoCommit是true,这里需要改成false。不然自己的事务粒度控制可能会不生效,原因是直接接默认提交了。