- 如何找到项目target路径?
- 利用Maven的pom.xml文件给出属性
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemPropertyVariables>
<io.springfox.staticdocs.outputDir>${swagger.output.dir}</io.springfox.staticdocs.outputDir>
<io.springfox.staticdocs.snippetsOutputDir>${swagger.snippetOutput.dir}</io.springfox.staticdocs.snippetsOutputDir>
</systemPropertyVariables>
</configuration>
</plugin>
代码可以按照如下方式获取属性值
String outputDir = System.getProperty("io.springfox.staticdocs.outputDir");
2. 利用application.properties文件位置
ClassPathResource pathfileRes = new ClassPathResource("application.properties");
projectDir = pathfileRes.getFile().getParentFile().getParentFile().getParentFile();
- 如何提供MockMvc所需要的json参数?
通过引入com.fasterxml.jackson.databind.ObjectMapper,如下生成Json:
private String createPet() throws JsonProcessingException {
Pet pet = new Pet();
pet.setId(1l);
pet.setName("Wuffy");
Category category = new Category(1l, "Hund");
pet.setCategory(category);
return new ObjectMapper().writeValueAsString(pet);
}
然后发出请求,
this.mockMvc.perform(post("/pets/").content(createPet())
.contentType(MediaType.APPLICATION_JSON))
- 为什么MockMvcBuilders生成的MockMvc没有生成文档,报null错误?
mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.build();
这时我们需要通过RestDocumentation来指定文档输入路径:
@Rule
public final RestDocumentation restDocumentation = new RestDocumentation("build/generated-snippets");
@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
.apply(documentationConfiguration(this.restDocumentation))
.build();
}
更加简洁的方式是通过annotation来定义路径:
@AutoConfigureRestDocs(outputDir = "build/asciidoc/snippets")
而MockMvc也可以对测试类配置注解@AutoConfigureMockMvc,通过@Autowired注入
this.mockMvc.perform(post("/pets/").content(createPet())
.contentType(MediaType.APPLICATION_JSON))
.andDo(document("addPetUsingPOST", preprocessResponse(prettyPrint())))
.andExpect(status().isOk());