Spring MockMvc测试:空指针异常

时间:2016-08-26 10:39:05

标签: spring-mvc nullpointerexception mockmvc spring-restdocs

我正在学习将Spring文档集成到我的项目中的教程,但是当我运行测试时,我遇到了nullpointerexception。

当我取出所有文档位时,错误消失了。因此,当我删除restDocumentation变量时,来自setup方法和测试的文档位然后传递。

这是我的测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class, classes = { ContextConfiguration.class })
@WebAppConfiguration
public class ApiDocs {

@Rule
public RestDocumentation restDocumentation = new RestDocumentation(
        "${project.basedir}/target/generated-snippets");

private RestDocumentationResultHandler document;

@Autowired
private WebApplicationContext context;

private MockMvc mockMvc;

@Autowired
Config Config;

@Before
public void setUp() {

    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
            .apply(documentationConfiguration(this.restDocumentation)).alwaysDo(this.document).build();

}

@Test
public void getConfig() throws Exception {

    this.mockMvc.perform(get("/config").accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk()).andDo(document("index"));
 }
 }

我得到的错误(由于隐私原因,我已经删除了我的课程包):

 java.lang.NullPointerException
 at org.springframework.test.web.servlet.MockMvc.applyDefualtResultActions(MockMvc.java:195)
 at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:163)
 at //.//.//.//.//.ApiDocs.getConfig(ApiDocs.java:67)
 at org.springframework.test.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
 at org.springframework.test.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
 at
org.springframework.restdocs.RestDocumentation$1.evaluate(RestDocumentation.java:59)
 at org.springframework.test.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
 at org.springframework.test.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
 at org.springframework.test.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
  at org.springframework.test.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:75)
  at org.springframework.test.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:75)
   at org.springframework.test.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)

1 个答案:

答案 0 :(得分:3)

没有任何内容为您的this.document字段分配值,因此它null。您已将其传递到alwaysDo,然后会导致NullPointerException

您需要配置您希望始终发生的事情。例如,将其添加到setUp方法的开头:

this.document = document("{method-name}", 
        preprocessRequest(removeHeaders("Foo")),
        preprocessResponse(prettyPrint()));

documentation中有关于此的更多信息。