1

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

当我取出所有文档位时,错误就消失了。因此,当我从设置方法和测试中删除 restDocumentation 变量、文档位时,它就会通过。

这是我的测试课

@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)
4

1 回答 1

3

没有什么可以为您的字段分配值,this.document所以它是null. 你正在传递那个alwaysDo然后导致一个NullPointerException.

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

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

文档中有更多关于此的信息

于 2016-08-26T13:07:10.770 回答