1

単体テストで単純なリクエストで 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;

}
}
}
4

1 に答える 1

1

提供されたコードを使用して、最初にスローされたjava.net.ConnectionExceptionを処理する必要がありました。テストの URL には、localhost のポートが必要です。 sendGet("http://localhost:8089/my/resource/121")

その後、404 が表示される理由は、正規表現がテスト URL と一致しないためだと思います。

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

する必要があります

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

「resource」と「[0-9]+」の間の追加のパス区切りに注意してください

regex101などの正規表現テスト用のオンライン ツールを使用して、パターン マッチングの動作をテストできます。(スラッシュをエスケープすることを忘れないでください)

パターン :\/my\/resource\/[0-9]+

テスト文字列:http://localhost:8089/my/resource/121

それが役立つことを願っています!

于 2016-05-17T01:06:32.463 に答える