WireMock is a simulator for HTTP-based APIs.
Maven Dependency 1 2 3 4 5 6 <dependency > <groupId > com.github.tomakehurst</groupId > <artifactId > wiremock-jre8</artifactId > <version > 2.26.3</version > <scope > test</scope > </dependency >
Non-Junit Usage You can use WireMock without Junit.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 import com.github.tomakehurst.wiremock.WireMockServer;import com.github.tomakehurst.wiremock.core.WireMockConfiguration;import static com.github.tomakehurst.wiremock.client.WireMock.*;public class MockServer { public static void main (String[] args) { WireMockServer wireMockServer = new WireMockServer (WireMockConfiguration.options().port(8090 ).httpsPort(8091 )); wireMockServer.start(); configureFor("localhost" , 8090 ); stubFor(get(urlEqualTo("/some/thing" )) .willReturn(aResponse() .withHeader("Content-Type" , "text/plain" ) .withBody("Hello world!" ))); } }
This will start a mock server with two endpoints. Both endpoints return Hello world!
Usage With Junit This rule will start the server before each tyest method and stop it afterwards.
1 2 @Rule public WireMockRule wireMockRule = new WireMockRule (WireMockConfiguration.options().port(8090 ));
Example Junit Test with WireMock
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 import com.github.tomakehurst.wiremock.core.WireMockConfiguration;import com.github.tomakehurst.wiremock.junit.WireMockRule;import com.jayway.jsonpath.JsonPath;import org.apache.http.HttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.junit.Assert;import org.junit.Rule;import org.junit.Test;import java.io.IOException;import java.io.InputStream;import java.util.Scanner;import static com.github.tomakehurst.wiremock.client.WireMock.*;public class MockServerTest { @Rule public WireMockRule wireMockRule = new WireMockRule (WireMockConfiguration.options().port(8090 )); @Test public void testServer () throws IOException { stubFor(get(urlPathMatching("/blah/.*" )) .willReturn(aResponse().withStatus(200 ) .withHeader("Content-Type" , "application/json" ) .withBody("{\"result\": \"success\"}" ))); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet request = new HttpGet ("http://localhost:8090/blah/wiremock" ); HttpResponse httpResponse = httpClient.execute(request); String stringResponse = convertResponseToString(httpResponse); Assert.assertEquals( "success" , JsonPath.<String>read(stringResponse, "$.result" )); } private String convertResponseToString (HttpResponse response) throws IOException { InputStream responseStream = response.getEntity().getContent(); Scanner scanner = new Scanner (responseStream, "UTF-8" ); String responseString = scanner.useDelimiter("\\Z" ).next(); scanner.close(); return responseString; } }
Reference