背景
单元测试时,一开始时这样写的
@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的上下文。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)