hahanizhu 2015-01-23 05:20 采纳率: 0%
浏览 2073

Spring MVC UT中的NPE

代码很简单,是对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的问题,不知道是不是

  • 写回答

2条回答 默认 最新

  • 微wx笑 Java领域优质创作者 2015-01-23 05:24
    关注

    此处需要注意 一定要ContextLoaderListener 才行 即只有它才能通过 ContextLoader.getCurrentWebApplicationContext(); 获取

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog