[英]Host website during integration test
我正在開發一個刮板,為此,我正試圖編寫一個集成測試來刮刮存儲在磁盤上的HTML。 測試應從img src抓取圖像URL。 在代碼中,這可以歸結為Jsoup.connect(url)
,其中url是一個字符串。 我知道模擬,但這不屬於集成測試。 這就是我認為托管網站並真正返回圖像是要走的路。 當然也歡迎其他選擇。
理想情況下,測試運行時將啟動占用空間小的Web服務器。 我應該能夠確定或至少知道其發布網站的網址。 我還應該能夠將Web服務器指向HTML文件。
scraper項目是一個Spring Boot。 我可以從/ static靜態地提供頁面,而不是由控制器解析。 當我有一個控制器返回頁面時,Thymeleaf解析了該頁面,並拋出org.xml.sax.SAXParseException: The entity name must immediately follow the '&' in the entity reference
。 為了看到這些結果,我運行了整個Spring Boot應用程序。
考慮在您的情況下使用WireMock ( http://wiremock.org/ )。 WireMock可幫助您運行HTTP服務器並在集成(或單元)測試環境中確定其行為。 看下面的示例(JUnit測試):
package com.github.wololock;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public final class WireMockHtmlTest {
@Rule
public WireMockRule wireMockRule = new WireMockRule(options().port(8080));
@Before
public void setup() throws IOException {
final InputStream inputStream = getClass().getClassLoader().getResourceAsStream("html/index.html");
final String html = new String(IOUtils.toByteArray(inputStream), Charset.forName("UTF-8"));
wireMockRule.stubFor(get(urlEqualTo("/index"))
.willReturn(aResponse()
.withBody(html)
.withHeader("Content-Type", "text/html; charset=UTF-8")
)
);
}
@Test
public void test() throws IOException, InterruptedException {
//given:
final URLConnection connection = new URL("http://localhost:8080/index").openConnection();
//when:
final String body = IOUtils.toString(connection.getInputStream(), Charset.forName("UTF-8"));
//then:
assertThat(body.contains("Hello world!"), is(equalTo(true)));
}
}
該測試加載存儲在src/test/resources/html/index.html
的HTML文件的內容,該文件包含:
<html>
<head>
<title>Hello world!</title>
</head>
<body>
<h1>Hello world!</h1>
</body>
</html>
如果要在集成測試中使用WireMock,只需要做幾件事:
WireMockRule
指定@Rule
(它處理正在運行的HTTP服務器)。 值得一提的是-使用未使用的端口號,否則服務器將無法啟動。 @Before
階段(你可以找到更多關於磕碰在這里- http://wiremock.org/docs/stubbing/ ) localhost
)的測試用例。 我故意粘貼了所有導入,以便您可以查看使用了哪些類。
希望能幫助到你 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.