Spring Cloud合同使用者|模拟OkHttp

时间:2018-08-07 11:22:12

标签: groovy spring-cloud-contract

我的主要班级是这样的:

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?

1 个答案:

答案 0 :(得分:2)

如果您使用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;
}
}

然后在测试中,您可以设置存根的端口和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。无论如何,希望它能向您显示如何解决该问题。

相关问题