跟着JHipster學做項目(1)- MockMvc用法技巧

  • 如何找到項目target路徑?
  1. 利用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());

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章