单元测试ContextLoader.getCurrentWebApplicationContext();返回null

在进行Spring MVC应用的单元测试时,遇到ContextLoader.getCurrentWebApplicationContext()返回null的困扰。解决方案包括在测试类上添加@WebAppConfiguration注解,并在@Before方法中初始化上下文。问题源于ContextLoader类依赖于web容器启动,通常通过web.xml配置ApplicationContext。

背景

单元测试时,一开始时这样写的

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:/applicationContext.xml")
public class BaseTest {
}

但是使用

ContextLoader.getCurrentWebApplicationContext()返回的确是null

经过研究

Write Junit tests for Spring MVC application which internally relies upon ContextLoader.getCurrentWebApplicationContext() - Stack Overflow

1.单元测试增加@WebAppConfiguration注解

2.增加@Before这段代码

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:/applicationContext.xml")
@WebAppConfiguration
public class BaseTest {
    @Autowired
    private WebApplicationContext wac;


    @Before
    public void setApplication(){
        MockServletContext sc = new MockServletContext("");
        ServletContextListener listener = new ContextLoaderListener(wac);
        ServletContextEvent event = new ServletContextEvent(sc);
        listener.contextInitialized(event);
    }
}

原因:

 ContextLoader类是web容器启动时,才会把ApplicationContext的上下文加载出来。即是通过web.xml文件中的org.springframework.web.context.ContextLoaderListener类来设置ApplicationContext的上下文。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值