2016-05-16 52 views
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; 

} 
} 
} 

回答

1

使用您提供的代碼,我首先必須處理java.net.ConnectionException正被拋出。您的測試網址需要本地主機上的端口。 sendGet("http://localhost:8089/my/resource/121")

之後,我認爲你得到404的原因是你的正則表達式不符合你的測試網址。

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

應該

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

記 '資源' 之間的額外路徑分隔符 '[0-9] +' 爲正則表達式

在線工具像regex101這樣的測試可以用來測試模式匹配行爲。 (記住逃避你正斜槓)

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

測試字符串:http://localhost:8089/my/resource/121

希望幫助!

+0

當我將端口設置爲8089時,它運行良好。不過,從更大的角度來看,我的單元測試中運行的是嵌入式Tomcat服務器。當我給tomm服務器使用相同的端口時,我會得到一個綁定錯誤,因爲端口已經被tomcat服務器使用。有沒有辦法讓這個工作進入tomcat端口的請求? – dwardu

+1

使用默認的Wiremock規則,我不認爲你所要求的可以在Junit環境中完成。可能還有其他選擇,但我並不十分熟悉這種情況。我最好的建議是通過電報文檔,看看有沒有什麼東西能適合你的用例。 http://wiremock.org/getting-started.html – Jeremiah

相關問題