membersound
membersound

Reputation: 86847

How to build get-query string for MockMvcRequestBuilders?

I'm using spring-boot-test with MockMvcRequestBuilders to test some GET rest webservice.

Question: is it possible to automatically translate a bean to a get-query?

Example:

@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;
}

I would need an auto translation to: ?firstname=john&lastname=doe&age=30, but in a more generic way not having to type the parameters statically.

Upvotes: 1

Views: 2920

Answers (1)

Andy Wilkinson
Andy Wilkinson

Reputation: 116171

I don't think there's anything available out-of-the-box for this specific requirement, but you can piece it together using a BeanWrapperImpl to access the properties from MyRequest and turn each into a call to param on the request builder:

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

Upvotes: 4

Related Questions