简体   繁体   English

如何模拟第三方 API 电话?

[英]How to mock third party API calls?

I have a spring boot application that has the below AuthFilter added for all rest apis exposed by the application.我有一个 spring 启动应用程序,它为应用程序公开的所有 rest api 添加了以下 AuthFilter。 I want to test the below code that validates authorization token by calling a third party api call.我想通过调用第三方 api 来测试下面验证授权令牌的代码。 I tried Mockito but how do I inject the mocked HttpPost, HttpClient etc object in the filter class?我尝试了 Mockito,但如何在过滤器 class 中注入模拟的 HttpPost、HttpClient 等 object? Also what value do I pass to thirdPartyAPIUrl property which is configured in application.properties for test class另外,我将什么值传递给在 application.properties 中配置的thirdPartyAPIUrl属性以进行测试 class

@Component
public class AuthTokenFilter implements Filter {

     public boolean isAuthTokenValid(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String authorizationToken = request.getHeader(RequestHeaders.AUTHORIZATION.toString());

        TokenRequest validateTokenRequest = new TokenRequest();
        validateTokenRequest.setToken(authorizationToken);


        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(this.thirdPartyAPIUrl); //fetched through application.properties
            httpPost.setHeader("Content-type", "application/json");
            StringEntity requestBody = new StringEntity(new Gson().toJson(validateTokenRequest));

            httpPost.setEntity(requestBody);
            try (CloseableHttpResponse validateTokenResponse = httpclient.execute(httpPost)) {
                HttpEntity rEntity = validateTokenResponse.getEntity();
                TokenResponse tokenResponse = new ObjectMapper().readValue(rEntity.getContent(),
                                                                                    TokenResponse.class);
                logger.debug("API Response Object : {}", tokenResponse);
            }
        }

        return false; //temporary
    }
}

Thanks!谢谢!

I would recommend avoiding mocking HttpPost etc and instead just mocking the third-party server.我建议避免使用 mocking HttpPost 等,而只使用第三方服务器 mocking。 My preferred tool to use for this is wiremock我首选的工具是wiremock

Here is an example of how it would be used:这是一个如何使用它的例子:

(make sure to import this for options, caused me a lot of headaches;) ) (确保为选项导入这个,让我很头疼;))

import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;

... code ... 代码

static WireMockServer wireMockServer = new WireMockServer(options().port(8080));

@BeforeAll
static void init() {
    wireMockServer.start();
}

//this is for the case that you have multiple test suites that mock the server, to avoid conflicts with ports
@AfterAll
static void releaseResource() {
        wireMockServer.stop();
    }

@Test
void test() {
    wireMockServer.stubFor(post("/endpoint").willReturn(aResponse().withStatus(200)));

... more code ... 更多代码

    filter.isAuthTokenValid(request, response);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM