如何使用 MockMvcRequestBuilders 在 Spring Boot 2.0 中向模型添加查询参数

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

我正在尝试使用 MockMvc 进行简单测试 class。但我陷入了一个非常简单的事情(但文档没有帮助)。

我的基本代码是

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

    }
  }

这样,代码运行正常,但是当我尝试使用参数化查询时,我找不到方法

我试过了(没有成功)

.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)

提前致谢

使用.param()

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

除了.param(),您还可以使用您已经尝试过的.get(String urlTemplate, Object... uriVars)。您非常接近解决方案:

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

也可以展开多个URI变量

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