工作两个月中,旧项目中虽然在每个代码汇中使用了 @Autowired @Qualifier注解,但是单元测试还是使用比较老旧的方法,
即 在每个TestCase里加上如下代码:
@Before
public void setUp() throws Exception {
ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:/spring/applicationContext.xml");
applymentService = (ApplymentService) ctx.getBean("applymentService");
}
这种方法,我会在每个test之前运行一遍,这样做极大影响测试效率, 而且即使在每个Test之前加上 @Rollback(false)注解,依然不会在数据完成之后进行数据回滚。
或许可以用最基本的spring事物进行回滚,但不能为了测试而测试,在单元测试的问题上,不应该把宝贵的时间浪费在这些事情上。
古人云,工欲善其事,必先利其器。springframeworks自带了优秀的测试框架 spring-test,基本能完成单元测试的要求。
使用方法如下:
一:加入依赖包
- spring-test
- spring其它依赖包
- junit4
二:编写相应要测试的bean,加入package-to-scan,(可以替换为base-package)
<context:component-scan base-package="org.stackbox.model.core" />
三:
基于spring-test的TestCase需继承一个父类,
AbstractJUnit4SpringContextTests 或者
AbstractTransactionalJUnit4SpringContextTests,后者可以用于事物处理,(但有人说使用前者时,在每个Test之前
加上 @Rollback(false)也能进行回滚,这种方法暂时没试)
四:对于使用AbstractTransactionalJUnit4SpringContextTests,需要在applicationContext.xml中配置transactionManager
具体配置视各个情况而定,如我操作数据库采用的是 spring.orm.hibernate的hibernateTemplate,我的配置就应该是
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
如果,我是自己操作jdbc,那么我的配置文件就应该是
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="jdbcDataSource" />
</bean>
package com.farmol.model.core.service;
import static org.junit.Assert.fail;
import javax.annotation.Resource;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.farmol.model.core.entity.Category;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/spring/applicationContext.xml")
public class CategoryServiceTest extends AbstractTransactionalJUnit4SpringContextTests {
@Resource
private CategoryService categoryService;
@Before
public void setUp() throws Exception {
}
@Test@Rollback(false)
public void testSave() {
Category category = new Category();
category.setCategoryName("茶");
category.setCreatedTime(new java.util.Date());
categoryService.save(category);
}
}
注意事项: AbstractTransactionalJUnitSpringContextTests 的每个 test前不加 @RollBack注解时,默认使用事物回滚,即,测试完成之后无法save数据