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

单元测试ContextLoader.getCurrentWebApplicationContext();返回null,第1张

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

背景

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

@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的上下文。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5685654.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存