Spring4+Junit4整合
Spring profile 常用方法与profile名称
摘自springside
/**
* Spring profile 常用方法与profile名称。
*
* @author calvin
*/
public class Profiles {
public static final String ACTIVE_PROFILE = "spring.profiles.active";
public static final String DEFAULT_PROFILE = "spring.profiles.default";
public static final String PRODUCTION = "production";
public static final String DEVELOPMENT = "development";
public static final String UNIT_TEST = "test";
public static final String FUNCTIONAL_TEST = "functional";
/**
* 在Spring启动前,设置profile的环境变量。
*/
public static void setProfileAsSystemProperty(String profile) {
System.setProperty(ACTIVE_PROFILE, profile);
}
}
封装Testcase
摘自springside 通过@ActiveProfiles指定环境
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
/**
* Spring的支持依赖注入的JUnit4 集成测试基类, 相比Spring原基类名字更短.
*
* 子类需要定义applicationContext文件的位置,如:
*
* @ContextConfiguration(locations = { "/applicationContext-test.xml" })
*
* @author calvin
*/
@ActiveProfiles(Profiles.PRODUCTION)
public abstract class SpringContextTestCase extends AbstractJUnit4SpringContextTests {
}
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
/**
* Spring的支持数据库访问, 事务控制和依赖注入的JUnit4 集成测试基类.
* 相比Spring原基类名字更短并保存了dataSource变量.
*
* 子类需要定义applicationContext文件的位置, 如:
*
* @ContextConfiguration(locations = { "/applicationContext.xml" })
*
* @author calvin
*/
@ActiveProfiles(Profiles.PRODUCTION)
public abstract class SpringTransactionalTestCase extends AbstractTransactionalJUnit4SpringContextTests {
protected DataSource dataSource;
@Override
@Autowired
public void setDataSource(DataSource dataSource) {
super.setDataSource(dataSource);
this.dataSource = dataSource;
}
}
TestCase
@ContextConfiguration(locations={"classpath:spring-context.xml"})
//有不用@RunWith也可以用的,自己没有测试
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
//如果是true不会改变数据库数据,如果是false会改变数据
@TransactionConfiguration(transactionManager="transactionManager",defaultRollback=true)
public class DingTest extends SpringTransactionalTestCase{
@Autowired
private DingUserService dingUserService;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void test() {
System.out.println(dingUserService+"------");
}
}