如何为MockMvcRequestBuilders构建get-query字符串?

时间:2018-07-18 15:29:59

标签: java spring spring-boot junit spring-test

我正在将spring-boot-testMockMvcRequestBuilders结合使用,以测试一些GET静态Web服务。

问题:是否可以将 bean 自动转换为get-query

示例:

@AutoConfigureMockMvc
public class WebTest {
    @Autowired
    protected MockMvc mvc;

    @Test
    public void test() {
        MyRequest req = new MyRequest();
        req.setFirstname("john");
        req.setLastname("doe");
        req.setAge(30);

        mvc.perform(MockMvcRequestBuilders
                .get(path)
                .contentType(MediaType.APPLICATION_JSON)
                .param(...) //TODO how to automatically add all params?
                .andExpect(status().isOk());
    }
}

public class MyRequest {
    private String firstname;
    private String lastname;
    private int age;
}

我需要自动转换为:?firstname=john&lastname=doe&age=30,但以更通用的方式不必静态键入参数。

1 个答案:

答案 0 :(得分:3)

我认为没有针对此特定需求的现成可用的东西,但是您可以使用BeanWrapperImpl将其组合在一起,以访问MyRequest的属性并将其转换为在请求构建器上对param的调用:

MyRequest req = new MyRequest();
req.setFirstname("john");
req.setLastname("doe");
req.setAge(30);

MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders
        .get(path).contentType(MediaType.APPLICATION_JSON);

for (PropertyDescriptor property : new BeanWrapperImpl(req).getPropertyDescriptors()) {
    if (property.getWriteMethod() != null) {
        requestBuilder.param(property.getName(),     
                property.getReadMethod().invoke(req).toString());
    }
}

mvc.perform(requestBuilder).andExpect(status().isOk());