可以利用
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=JPortContextLoader.class,locations = { "/system/test-applicationContext.xml",
"/system/applicationContext-spring-security-hibernate.xml",
})
来加载spring配置文件。注意JPortContextLoader为自定义的,符合ContextLoader即可,需要这样写:
public class JPortContextLoader implements ContextLoader {
@Override
public ApplicationContext loadContext(String... paths) throws Exception {
System.out.println("load");
ApplicationContext ctx =
new FileSystemXmlApplicationContext(wholePaths.toArray(new String[0]));
return ctx;
}
@Override
public String[] processLocations(Class<?> arg0, String... arg1) {
System.out.println("processLocations"+arg1);
//处理配置的locations
return arg1;
}
}
注意:即使在processLocations中什么都没处理,也必须返回arg1那个参数,否则就运行不了。
主要是默认的ContextLoader只能取classpath中的,我也没有找到能取文件系统的,就扩展了一个,在TestContext类中,先执行
processLocations
方法处理配置的locations,然后再执行
loadContext
来获得ApplicationContext。
对于需要回滚事务的继承下Spring的抽象类即可:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=JPortPentahoContextLoader.class,locations = { "/system/test-applicationContext.xml",
"/system/applicationContext-spring-security-hibernate.xml"
})
public class PentahoTransactionalJUnit4SpringContextTests extends
AbstractTransactionalJUnit4SpringContextTests {
然后其他类只要继承这个基类就可以来,然后
@TransactionConfiguration(defaultRollback = true)注解还可以写在子类里,即具体的测试用例中。
另外我还使用@Autowired注解,这需要在配置文件中写上点东西。见下面的链接:
http://www.mkyong.com/spring/spring-auto-wiring-beans-with-autowired-annotation/
我们的项目配置文件不在Classpath中,如果想利用Spring的测试框架就有点别扭,过去都是使用Eclipse的link source来搞,但是团队开发时非常别扭,因为link source是指向绝对路径的,大家的不一样,而且我使用linux开发,这样也不相同。
另外一点,运行环境使用JNDI配置SessionFactory,而开发环境IDE使用非JNDI配置,于是就建了一个test-applicationContext.xml,它和main-applicationContext的区别就是运行环境和IDE环境的不同,然后它作为一个集成性质的配置,其他的配置都通过import resource的方式。
源代码万岁