【轉】SpringTest框架JUnit單元測試用例獲取ApplicationContext實例的方法


轉自:http://www.coderli.com/junit-spring-test-applicationcontext

JUnit單元測試用例中使用Spring框架,直接方式如下。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/spring/applicationContext.xml" })
public class SpringTest {}

想要獲取ApplicationContext實例。可以添加了對ApplicationContext的注入

RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/spring/applicationContext.xml" })
public class SpringTest {
 
@Autowired
protected ApplicationContext ctx;

Spring中早已直接提供了更加方便使用的基類:AbstractJUnit4SpringContextTests

@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);
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM