代码很简单,是对Srping MVC工程controller的一个测试,用的Junit框架。测试代码如下
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.ContextHierarchy;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextHierarchy({
@ContextConfiguration(name="parent",locations="classpath:spring-test.xml"),
@ContextConfiguration(name="child", locations="classpath:spring-test-web.xml")
})
public class MomUserInfoControllerTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@Before
public void setUp() throws Exception {
mockMvc=MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void testBriefUser() throws Exception {
mockMvc.perform(get("/briefUser/3")).andDo(MockMvcResultHandlers.print()).andReturn();
}
但是这个case抛出了NPE,原因是我有个spring的拦截器,从request中取得一些信息,代码如下:
@Component
public class I18nInterceptor extends AbstractInterceptor {
private static final Logger logger = LoggerFactory.getLogger(I18nInterceptor.class);
@Autowired
private HttpServletRequest request;
@Override
public void preInvoke(MethodInvocation invocation) {
WebApplicationContext wc =ContextLoader.getCurrentWebApplicationContext();
RequestInfo requestInfo = wc.getBean("requestInfo", RequestInfo.class);
String locale = request.getParameter("locale");
logger.info("Set the locale to " + locale);
问题来了..wc是空值,就是ContextLoader.getCurrentWebApplicationContext();娶不到值,因此该测试会有空指针,也无法进行下去。不知道大家有啥办法解决?我想应该是@RunWith(SpringJUnit4ClassRunner.class)这个注解导致了这个启动的webapplicationcontext的问题,不知道是不是