首页 > 代码库 > SpringTest框架JUnit单元测试用例获取ApplicationContext实例的方法

SpringTest框架JUnit单元测试用例获取ApplicationContext实例的方法

步骤
1、继承AbstractJUnit4SpringContextTests
2、引入ApplicationContext


示例代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/spring/applicationContext.xml" })
public class SpringTest extends AbstractJUnit4SpringContextTests {
 
    @Autowired
    protected ApplicationContext ctx;
 
    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;
    }
}



来自为知笔记(Wiz)


SpringTest框架JUnit单元测试用例获取ApplicationContext实例的方法