成功解决util.NestedServletException: Request processing failed; nested exception is NullPointerException

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException

今天使用MockMvc框架进行controller的测试,遇到以上问题,频繁翻车!!!查来查去没有解决,写下此文帮助遇到问题的小伙伴!我个人不怎么写博客,没有排版的经验,也不会用那个markdown写(没研究过这个的写法),所以排版比较丑,小伙伴们谅解一下,抽取关键的看。好了,发车!!!

先来一张我最初的报错图,我最初写的测试类是这样子的,这个接口没有传入参数,因此不需要携带参数那些写法

成功解决util.NestedServletException: Request processing failed; nested exception is NullPointerException_第1张图片

 再看一下我类上面的信息

成功解决util.NestedServletException: Request processing failed; nested exception is NullPointerException_第2张图片

 描述一下我遇到问题的经过:

原先在init方法上使用的是@BeforeTest注解,导致context注入不进来,后改为@BeforeClass成功将context注入进来了,对于注入context上下文的方式可以测试所有的controller。

然后就可以通过编写测试类来测试了

成功解决util.NestedServletException: Request processing failed; nested exception is NullPointerException_第3张图片

控制台打印出下列信息

成功解决util.NestedServletException: Request processing failed; nested exception is NullPointerException_第4张图片

 还有人提到了单个Controller测试的方式,这样子的话可以看一下方法怎么样,看到网上有使用new的方式来创建controller,这是误人子弟的。正确的方式是

成功解决util.NestedServletException: Request processing failed; nested exception is NullPointerException_第5张图片

推荐使用上面提到的第一种方式,即注入WebApplicationContext的方式。

 

本人用的是TestNG框架的,所以在类上方的注解@RunWith(SpringRunner.class)里面的值就不是Junit4那些什么的啦。

 

关于Mockmvc的使用,推荐看一下下面这篇博客:

https://my.oschina.net/sdlvzg/blog/1594821

你可能感兴趣的:(问题解决方案)