跟着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());

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值