简体   繁体   English

使用wiremock时连接被拒绝

[英]Connection refused when using wiremock

I have this piece of code in a Junit, where I clearly set the port to 8888我在 Junit 中有这段代码,我清楚地将端口设置为 8888

when(clientUtils.getLinkUrl(eq(HOSTELS_MICROSERVICE.name()), eq(HOSTELS_MICROSERVICE.name()), anyMap()))
                .thenReturn("http://localhost:8888/HOSTELS/HOSTELSMethods");

stubFor(com.github.tomakehurst.wiremock.client.WireMock.get("/HOSTELS/HOSTELS_LIST").willReturn(
                aResponse().withStatus(200)
                        .withHeader("Content-Type", APPLICATION_JSON_VALUE)
                        .withBody(ResourceUtils.getResourceFileAsString ("__files/HOSTELS.json"))));

but when I run the test I got this error on this line:但是当我运行测试时,我在这一行得到了这个错误:

stubFor(com.github.tomakehurst.wiremock.client.WireMock.get("/HOSTELS/HOSTELS_LIST").willReturn(..

and the error:和错误:

wiremock.org.apache.http.conn.HttpHostConnectException: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect

For Java users对于 Java 用户

Based on the WireMock docs.基于WireMock文档。

There are 3 possibilities to use WireMock in your tests :在您的测试中使用 WireMock 有 3 种可能性:

  1. If you are using Wiremock as JUnit 4 rule to configure the port use :如果您使用 Wiremock 作为 JUnit 4 规则来配置端口,请使用:
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;

...

@Rule
public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().port(8888));
  1. If you are using new instance and start it from your Test class (for example @Before ) :如果您正在使用新实例并从您的 Test 类启动它(例如@Before ):
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;

...

public class Test {

    WireMockServer wm;

    @BeforeEach
    void setUp() {
        wm = new WireMockServer(options().port(8888));
        wm.start();
    }

    @Test
    void test() {
        wm.stubFor(...);
    }
}
  1. With static configuration of default instance (not using new instance in your test) :使用默认实例的静态配置(不在测试中使用新实例):
WireMock.configureFor(8888);

For Kotlin users对于 Kotlin 用户

If you are using kotlin you can add actual wiremock instance to stubFor and verify calls like wm.stubFor() and configure the port like in option 3 of this answer.如果您使用的是 kotlin,则可以将实际的 wiremock 实例添加到stubForverify wm.stubFor()之类的调用,并像此答案的选项 3 中那样配置端口。

Posting my previous comment as an answer as it seems to have helped a few people.发布我之前的评论作为答案,因为它似乎帮助了一些人。 Thanks @jmrah.谢谢@jmrah。 :) :)

For Kotlin and JUnit5 , this can be resolved by adding the actual WireMockServer instance to the stubFor or verify method calls.对于KotlinJUnit5 ,这可以通过将实际的WireMockServer实例添加到stubForverify方法调用来解决。

wireMockServer.stubFor()

or或者

wireMockServer.verify()

After adding this, the tests should work.添加后,测试应该可以工作。

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

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