Sourcerer
Sourcerer

Reputation: 2148

How to add query parameters to mockup in Spring Boot 2.0 with MockMvcRequestBuilders

I'm trying to do a simple test class using MockMvc. But I'm stuck in a really simple thing (but the docs doesn't help).

My basic code is

  @SpringBootTest
  @AutoConfigureMockMvc
  class RecommendationServiceApplicationTests {
    private static final Logger LOG = LoggerFactory.getLogger(RecommendationServiceApplicationTests.class);
    
    private final String url = "/recommendation?productId=%d";
    static final int PRODUCT_OK = 1;
    static final int PRODUCT_KO = 0;
    static final int PRODUCT_NOT_FOUND = 113;

    @Autowired
    private MockMvc mockMvc;

    // Check OK response
    @Test
    public void getRecommendationsOK() throws Exception {
        MockHttpServletRequestBuilder requestBuilder;
        MvcResult result;
        String contentResponse;
        Recommendation[] recommendations;

        requestBuilder=
        MockMvcRequestBuilders
            .get("/recommendation?productId=1")
            .accept(MediaType.APPLICATION_JSON);

        result = this.mockMvc
            .perform(requestBuilder)
            .andDo(MockMvcResultHandlers.print())
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andReturn();

    }
  }

In this way, the code runs fine, but when I try to use a parameterized query, I cannot find the way

I have tried (with no success)

.get("/recommendation?productId=",PRODUCT_OK)
.get("/recommendation?productId={}",PRODUCT_OK)
.get("/recommendation?productId=%d",PRODUCT_OK)
.get("/recommendation?productId=[]",PRODUCT_OK)
.get("/recommendation?productId=PRODUCT_OK",PRODUCT_OK)

Thanks in advance

Upvotes: 3

Views: 1198

Answers (2)

rieckpil
rieckpil

Reputation: 12031

Apart from .param(), you can also use the .get(String urlTemplate, Object... uriVars) that you already tried. You were pretty close to the solution:

.get("/recommendation?productId={product}",PRODUCT_OK)

You can also expand multiple URI variables

.get("/recommendation?productId={product}&sort={var}",PRODUCT_OK, "desc");

Upvotes: 6

Nakul Goyal
Nakul Goyal

Reputation: 659

Use .param()

MockMvcRequestBuilders
            .get("/recommendation")
            .param("product", "1")
            .accept(MediaType.APPLICATION_JSON);

Upvotes: 1

Related Questions