Launch WireMock with mappings file of JUnit

在解決整合REST外部服務的腳本錄製問題後,接下來就是應用的問題。我想要解決的問題是「該如何在JUnit中啟用預錄好的腳本,讓它取代我所相依的外部服務,讓測試更穩更快減少假警報呢?」本篇分享我的做法。

WireMockRule

這個方法是官網教的,直接使用JUnit的Rule讓它幫你啟動與關閉WireMockServer;如果要載入預錄腳本,就直接指定mappings的上一層即可。以我的範例來說,預錄腳本是放在./testdata/loadMappings/query/mappings中:

public class TestWithWireMockRule {
	@Rule
	public WireMockRule wireMockRule = new WireMockRule(WireMockConfiguration.options()
			.port(80)
			.httpsPort(443)
			.usingFilesUnderDirectory("./testdata/loadMappings/query"));
 
	@Test
	public void getHttpCode200WhenQueryUser() throws IOException {
		HttpGet post = new HttpGet("http://localhost/api/users/2");
		CloseableHttpClient httpClient = HttpClientFactory.createClient();
		try {
			CloseableHttpResponse response = httpClient.execute(post);
			assertEquals(200, response.getStatusLine().getStatusCode());
		} finally {
			httpClient.close();
		}	
	}
}

WireMockServer

如果想要在不同測試案例中,載入不同的腳本,可以自己控制WireMockServer啟動與關閉。寫法和WireMockRule大同小異,因為它其實是extendWireMockServer的。

public class TestWithWireMockServer {
	private WireMockServer wireMockServer;
 
	@After
	public void teardown() {
		wireMockServer.stop();
	}
 
	private void launchWireMockServer(String testdataPath) {
		wireMockServer = new WireMockServer(WireMockConfiguration.options()
				.port(80)
				.httpsPort(443)
				.usingFilesUnderDirectory(testdataPath));
		wireMockServer.start();
	}
 
	@Test
	public void getHttpCode200WhenQueryUser() throws IOException {
		launchWireMockServer("./testdata/loadMappings/query");
 
		HttpGet post = new HttpGet("http://localhost/api/users/2");
		CloseableHttpClient httpClient = HttpClientFactory.createClient();
		try {
			CloseableHttpResponse response = httpClient.execute(post);
			assertEquals(200, response.getStatusLine().getStatusCode());
		} finally {
			httpClient.close();
		}	
	}
 
	@Test
	public void getHttpCode200WhenUpdateUser() throws IOException {
		launchWireMockServer("./testdata/loadMappings/update");
 
		HttpPatch patch = new HttpPatch("http://localhost/api/users/2");
		patch.setEntity(new StringEntity("{\"name\":\"morpheus\",\"job\":\"zion resident\"}", "utf-8"));
		CloseableHttpClient httpClient = HttpClientFactory.createClient();
		try {
			CloseableHttpResponse response = httpClient.execute(patch);
			assertEquals(200, response.getStatusLine().getStatusCode());
		} finally {
			httpClient.close();
		}	
	}
}