0
我試圖讓我的單元測試返回200狀態與簡單的請求,但是,這個單元測試總是返回一個404錯誤。Wiremock測試總是得到一個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;
}
}
}
當我將端口設置爲8089時,它運行良好。不過,從更大的角度來看,我的單元測試中運行的是嵌入式Tomcat服務器。當我給tomm服務器使用相同的端口時,我會得到一個綁定錯誤,因爲端口已經被tomcat服務器使用。有沒有辦法讓這個工作進入tomcat端口的請求? – dwardu
使用默認的Wiremock規則,我不認爲你所要求的可以在Junit環境中完成。可能還有其他選擇,但我並不十分熟悉這種情況。我最好的建議是通過電報文檔,看看有沒有什麼東西能適合你的用例。 http://wiremock.org/getting-started.html – Jeremiah