首页 > 解决方案 > Spring Cloud 合约消费者 | 模拟 OkHttp

问题描述

我的主要课程是这样的:

class MyClass{

    String bar(String inputString){
        String url = "https:x.y.z/p/q";  //the URL is framed dynamically based on other class attributes
        final String payloadInJson = getPayload(inputString)
        final String response = doPostRequest(url, payloadInJson)
    }

    private static String doPostRequest(final String url, final String postData) throws IOException {
        final RequestBody body = RequestBody.create(JSON, postData)
        final Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build()
        final Response response = createOkHttpClient().newCall(request).execute()
        if (!response.isSuccessful()) {
            throw new RuntimeException("...")
        }
        response.networkResponse().header("Location")
    }


    private static OkHttpClient createOkHttpClient() {
        Config config = new ConfigBuilder()
                .withTrustCerts(true)
                .build()
        def httpClient = HttpClientUtils.createHttpClient(config)
        httpClient = httpClient.newBuilder().authenticator(Authenticator.NONE).build()
        httpClient
    }

}

我的消费者测试用例是:

@SpringBootTest(classes = Application.class)
@AutoConfigureStubRunner(stubsMode = StubRunnerProperties.StubsMode.LOCAL, ids = ["com.ex:foobar:+:stubs:8090"])
class MyClassTest{
     @Inject
     private MyClass myClass

     def 'happyPath'(){
         given:
         ...
         when:
            String res = myClass.bar('lorem...')
     }
}

问题是如何模拟 OkHttp URL 并使用 localhost?还是在测试用例中,我可以参考实际的 URL 框架?

标签: groovyspring-cloud-contract

解决方案


如果您使用 Spring Cloud Contract,我们会在给定或随机端口上启动 HTTP 服务器。将 OK Http Client 设置为指向已启动的服务器就足够了。例子

伪代码:

class MyClass{
private String url = "https:x.y.z/p/q";

String bar(String inputString){
        final String payloadInJson = getPayload(inputString)
        final String response = doPostRequest(this.url, payloadInJson)
    }

// package scope
void setUrl(String url) {
this.url = url;
}
}

然后在您的测试中,您可以设置存根的端口和网址

测试(再次伪代码):

@SpringBootTest(classes = Application.class)
@AutoConfigureStubRunner(stubsMode = StubRunnerProperties.StubsMode.LOCAL, ids = ["com.ex:foobar"])
class MyClassTest{
     @Inject
     private MyClass myClass

     @StubRunnerPort("foobar") int stubPort;

     def 'happyPath'(){
         given:
         myClass.url = "http://localhost:${stubPort}"
         when:
            String res = myClass.bar('lorem...')
     }
}

更好的选择是使用适当的@Configuration类来定义 bean 并通过构造函数注入 URL。无论如何,希望它向您展示如何解决问题。


推荐阅读