1

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

Sourcerer
  • 1,891
  • 1
  • 19
  • 32

2 Answers2

4

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");
rieckpil
  • 10,470
  • 3
  • 32
  • 56
1

Use .param()

MockMvcRequestBuilders
            .get("/recommendation")
            .param("product", "1")
            .accept(MediaType.APPLICATION_JSON);
Nakul Goyal
  • 593
  • 4
  • 12
  • I did this way, but, do you know how to use 'get' for doing this? Or is it not possible? – Sourcerer Dec 01 '20 at 18:19
  • 1
    Yes it is possible, .get("/recommendation?product={p}", 1) same as shared by @rieckpil It's better to use .param() for more readability. – Nakul Goyal Dec 03 '20 at 10:10