首页 > 解决方案 > 尝试调用 Wiremock Stub 时连接被拒绝

问题描述

我正在尝试将 Cucumber-JVM 与 WireMock 集成,并且我不断得到

java.net.ConnectException: Connection refused: connect

我已经尝试了几个教程,包括来自 cucumber.io的官方文档,并且还尝试了以下这些:

Baeldung 的 WireMock 简介

来自 StackOverflow 的东西

Wiremock Github 问题页面

我的 Gradle 依赖项:

implementation 'org.springframework.boot:spring-boot-starter-web'   
testImplementation 'io.cucumber:cucumber-java:6.2.2'
testImplementation 'io.cucumber:cucumber-junit:6.2.2'
testImplementation 'io.rest-assured:spring-web-test-client:4.3.1'
testCompile "com.github.tomakehurst:wiremock-jre8:2.27.0"
compile group: 'io.cucumber', name: 'cucumber-spring', version: '6.4.0'

基本思想是模拟服务器响应,所以将来我将能够在几个微服务之间创建一些集成测试。这个想法来自一本书,当时我正在阅读 The Cucumber for Java Book 如果有更好的方法来测试微服务,我愿意接受新的想法。

我有一个带有我的步骤定义的测试类,它从属性文件中获取端口信息。如下所示:

@SpringBootTest
@CucumberContextConfiguration
public class ConnectionWithCucumber {

    @Value("${another.server.port}")
    private int PORT;

    @Rule
    private WireMockRule wireMockRule = new WireMockRule(PORT);

    private String messageResult;

    @Given("I want to read a message")
    public void iWantToRead() {
        createMessageStub();
    }

    @When("I send the request")
    public void iSendTheRequest() {
        messageResult = given().get("localhost:8082/message").getBody().asString();
    }

    @Then("I should be able to read the word {string}")
    public void iShouldBeAbleToReadTheWord(String arg0) {
        assertEquals(arg0, messageResult);
    }

    private void createMessageStub() {
        wireMockRule.stubFor(get(urlEqualTo("/message"))
                .withHeader("Accept", equalTo("application/json"))
                .willReturn(aResponse()
                        .withStatus(200)
                        .withHeader("Content-Type", "application/json")
                        .withBody("message")));
    }
}

我还创建了一个带有可运行示例的存储库。

如果您没有找到 README 文件,在查看 repo 时,您可以使用以下命令运行项目:

./gradlew cucumber

或者如果您在 Windows 上:

gradle cucumber

在我让它工作之后,我重构了代码并将示例留在了我上面链接的存储库中,如果你有同样的问题,请检查它。

标签: javaspringgradlecucumber-jvmwiremock

解决方案


java.net.ConnectException:连接被拒绝:连接这意味着没有服务在监听端口请尝试打印服务正在运行的端口并检查。我可以看到你已经检查过wiremock是否正在运行请检查端口

您可以像这样添加测试属性。这将覆盖默认的 application.properties

    @TestPropertySource(properties = {
        "application.location=http://localhost:8082/app/api/v1/"

})

请将该行中的 url 更改为

 Header header = new Header("Accept","application/json")
 messageResult = given().header(header).port(8082).get("/message").getBody().asString();

代替

  messageResult = given().get("localhost:8082/message").getBody().asString();

它对我有用

@SpringBootTest
@CucumberContextConfiguration
public class ConnectionWithCucumber {

    @Value("${another.server.port}")
    private int PORT;


    @Rule
    private WireMockRule wireMockRule = new WireMockRule(8082);

    private WireMockServer wireMockServer = new WireMockServer(8083);


    private String messageResult;

    @Value("${test.word}")
    private String word;

    @Value("${test.number}")
    private String number;

    @Test
    public void testWord(){
        wireMockServer.start();
        wireMockRule.start();
        wireMockRule.isRunning();
        wireMockServer.isRunning();
        System.out.println(wireMockRule.port());
        assertThat(word).isEqualTo("word");
        assertThat(number).isEqualTo("number");
    }


    @Given("I want to read a message")
    public void iWantToRead() {
        wireMockServer.start();
        wireMockRule.start();
        wireMockRule.isRunning();
        wireMockServer.isRunning();
        System.out.println("wireMockRule port " + wireMockRule.port());
        System.out.println("wireMockServer port " + wireMockServer.port());

        // Start the stub
        createMessageStubServer();
        createMessageStub();

        wireMockServer.getStubMappings();
        wireMockRule.getStubMappings();
    }

    @When("I send the request")
    public void iSendTheRequest() {
        System.out.println("iSendTheRequest" + wireMockRule.isRunning());
        System.out.println("iSendTheRequest" + wireMockServer.isRunning());
        Header header = new Header("Content-Type","application/json");
        messageResult = given().port(8082).and().header("Accept","application/json").and()
                .get("/message").getBody().asString();

        System.out.println(messageResult);

    }

    @Then("I should be able to read the word {string}")
    public void iShouldBeAbleToReadTheWord(String arg0) {
        System.out.println(messageResult);
        System.out.println("arg0"+arg0);
        assertEquals(arg0, messageResult);
    }

    private void createMessageStub() {
        wireMockRule.stubFor(get(urlEqualTo("/message"))
                .withHeader("Accept", equalTo("application/json"))
                .willReturn(aResponse()
                        .withStatus(200)
                        .withHeader("Content-Type", "application/json")
                        .withBody("Response")));
    }

    private void createMessageStubServer() {
        wireMockServer.stubFor(get(urlEqualTo("/message"))
                .withHeader("Accept", equalTo("application/json"))
                .willReturn(aResponse()
                        .withStatus(200)
                        .withHeader("Content-Type", "application/json")
                        .withBody("{\"message\":\"1\"}")));
    }
}

这是您正在使用线模拟规则和线模拟服务器的工作代码,我们不需要根据文档同时使用两者您可以单独使用线模拟规则,这足以在每次测试之前启动和停止服务器

请参考 http://wiremock.org/docs/getting-started/

不要使用随机端口,因为这个测试用例可能会在其他环境中失败,使用固定端口,就像你对代码所做的那样

您可以使用wiremock规则或使用@AutoConfigureWireMock的spring方式,它将自动注入依赖项,因此spring将启动和停止模拟服务器而不是junit。

有关弹簧线模拟文档,请参阅https://cloud.spring.io/spring-cloud-contract/reference/html/project-features.html#features-wiremock

这里要注意的另一件事 @Rule 在 spring 之前执行,因此它没有获取端口值,因为 @Rule 属于 junit,您只需在 @Rule 注释中硬编码端口,或者您可以使用 @AutoConfigureWireMock 这就是我拥有的原因硬编码它


推荐阅读