Spring TestフレームJUnitユニットテストケースAplicationContextのインスタンスを取得する方法
3702 ワード
回転:http://www.coderli.com/junit-spring-test-applicationcontext
JUnitユニットのテストケースではSpringフレームを使用していますが、直接的な方法は以下の通りです。
静的なクラスで参照が必要な場合は、以下の方法しか使えません。
JUnitユニットのテストケースではSpringフレームを使用していますが、直接的な方法は以下の通りです。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/spring/applicationContext.xml" })
public class SpringTest {}
Application Contectの例を取得したいです。Application Contectへの注入を追加できます。RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/spring/applicationContext.xml" })
public class SpringTest {
@Autowired
protected ApplicationContext ctx;
Springでは、より便利なベースを直接提供しています。@ContextConfiguration(locations = { "/spring/applicationContext.xml" })
public class SpringTest extends AbstractJUnit4SpringContextTests {
public <T> T getBean(Class<T> type) {
return applicationContext.getBean(type);
}
public Object getBean(String beanName) {
return applicationContext.getBean(beanName);
}
protected ApplicationContext getContext() {
return applicationContext;
}
}
追加:静的なクラスで参照が必要な場合は、以下の方法しか使えません。
public class TPlatformInfoTest extends TestBase{
private static MyHttpClient TPlatformInfoDispose;
@BeforeClass
public static void setUpBeforeClass(){
System.out.println("***********here init first***************");
TPlatformInfoDispose = new MyHttpClient("platform");
DataSourceContextHolder.setDbType("ds2");
ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:WEB-INF/rest-*.xml");
pfm = ctx.getBean(TPlatformInfoMapper.class);
dim = ctx.getBean(TDeviceInfoMapper.class);
}