testing - Wiremock 测试总是在一个简单的请求上得到 404

标签 testing junit wiremock

我试图让 wiremock 在我的单元测试中通过一个简单的请求返回 200 状态,但是,这个单元测试总是返回 404 错误。

如何解决?

import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.junit.Assert.assertTrue;

import com.github.tomakehurst.wiremock.junit.WireMockRule;
import org.junit.Rule;
import org.junit.Test;

import java.net.HttpURLConnection;
import java.net.URL;

public class WiremockTest {

@Rule
public WireMockRule wireMockRule = new WireMockRule(8089); // No-args constructor defaults to port 8080

@Test
public void exampleTest() throws Exception {
    stubFor(get(urlPathMatching("/my/resource[0-9]+"))
            .willReturn(aResponse()
                    .withStatus(200)
                    .withHeader("Content-Type", "text/xml")
                    .withBody("<response>Some content</response>")));

    int result = sendGet("http://localhost/my/resource/121");
    assertTrue(200 == result);

    //verify(getRequestedFor(urlMatching("/my/resource/[a-z0-9]+")));
}

private int sendGet(String url) throws Exception {
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // optional default is GET
    con.setRequestMethod("GET");

    int responseCode = con.getResponseCode();
    return responseCode;

}
}
}

最佳答案

使用您提供的代码,我首先必须处理抛出的 java.net.ConnectionException。您的测试 url 需要本地主机上的端口。 sendGet("http://localhost:8089/my/resource/121")

在那之后,我认为您收到 404 的原因是您的正则表达式与您的测试网址不匹配。

urlPathMatching("/my/resource[0-9]+")

should be

urlPathMatching("/my/resource/[0-9]+")

note the additional path separator between 'resource' and '[0-9]+'

用于正则表达式测试的在线工具,例如 regex101可用于测试模式匹配行为。 (记得转义你的正斜杠)

模式:\/my\/resource\/[0-9]+

测试字符串:http://localhost:8089/my/resource/121

希望对您有所帮助!

关于testing - Wiremock 测试总是在一个简单的请求上得到 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37263089/

相关文章:

testing - 如何在 Cypress 中检查一个元素的多个 CSS 类?

java - 如何将 DataSource 绑定(bind)到 InitialContext 以进行 JUnit 测试?

java - Selenium:submit() 工作正常,但 click() 不工作

java - SSLHandshakeException 没有共同的密码套件 - linux 仅使用 wiremock

arrays - Python - 针对标量值测试数组中的所有值

testing - intern.js 如何测试遗留的非模块化代码

PHPUnit 进度点在新行中并显示 "wrong"百分比

java - JUnit 测试用例未通过 Maven 运行

java - WireMockRule 在集成测试中不适用于非本地主机

java - 使用 WireMock 测试 Spring JUnit 中的多个应用程序上下文