小编mad*_*ngi的帖子

MockRestServiceServer 如何仅验证不包括查询字符串的请求路径

我有一个@ComponentDataClientImpl,它使用RestTemplate. API端点具有查询参数,这些参数在调用时传递RestTemplate。有一个@RestClientTestTest 类DataApiClientImplTest测试DataClientImpl,使用 模拟 REST 调用MockRestServiceServer

在测试方法中,我想验证 API 调用中是否使用了正确的端点路径和查询参数(特别是名称)。使用MockRestRequestMatchers.requestTo()MockRestRequestMatchers.queryParam()方法进行验证。

MockRestRequestMatchers.requestTo()运行测试时失败。它似乎将包含查询字符串的实际 url 与不带查询字符串的预期 url(传递给MockRestRequestMatchers.requestTo()method.

在pom中,我正在使用

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.6.0</version>
    <relativePath/> 
</parent>
Run Code Online (Sandbox Code Playgroud)

代码如下。

@RestClientTest(DataApiClientImpl.class)
@AutoConfigureWebClient(registerRestTemplate = true)
class DataApiClientImplTest {

    private static final String OBJECT_ID_URI = "http://localhost:8080/testBucketId/objects/test-obj-id";

    @Autowired
    private DataApiClientImpl dataApiClientImpl;

    @Autowired
    private MockRestServiceServer mockRestServiceServer;

    @Test
    void testApiCall() {
        mockRestServiceServer.expect(MockRestRequestMatchers.requestTo(OBJECT_ID_URI))
                .andExpect(MockRestRequestMatchers.method(HttpMethod.GET))
                .andExpect(MockRestRequestMatchers.queryParam("keyid", CoreMatchers.anything()))
                .andExpect(MockRestRequestMatchers.queryParam("token", CoreMatchers.anything()))
                .andRespond(MockRestResponseCreators.withSuccess("dummy", MediaType.APPLICATION_JSON));

        String response = dataApiClientImpl.getItem("asdf12345", …
Run Code Online (Sandbox Code Playgroud)

java resttemplate spring-boot mockrestserviceserver

6
推荐指数
2
解决办法
3618
查看次数