在进行单元测试的时候,有时候需要测试Web项目启动的相关初始化操作,即执行contextIntialized(ServletContextEvent event)操作,主要的一个问题点ServletContextEvent。
一种解决方案是直接new一个,但是需要一个ServletContext对象,就直接通过WebApplicationContext获取了。可是在通过自动获取WebApplicationContext对象的时候报了java.lang.NoClassDefFoundError: javax/servlet/SessionCookieConfig这个错误,这是因为Spring与Servlet版本不兼容引起的,在测试范围内引入高版本的Servlet即可。
测试代码:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.contest.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.context.WebApplicationContext;
import javax.servlet.ServletContext;
import javax.servlet.SerletContextEvent;
@Runner(SpringJunit4ClassRunner.class)
@ContextConfiguration(locations &#