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(); 获取

    评论

报告相同问题?

悬赏问题

  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图