Show List

Using Wiremock

Here's an example of how you can use WireMock to create a mock HTTP service:

  • First, you need to download and install WireMock. You can download the standalone JAR file from the official website, or you can use a build tool like Maven or Gradle to manage your dependencies.

  • Next, you'll need to create a new instance of the WireMock server. This can be done using the following code:

java
Copy code
import com.github.tomakehurst.wiremock.WireMockServer; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; WireMockServer wireMockServer = new WireMockServer(wireMockConfig().port(8080)); wireMockServer.start();

This will start a new instance of the WireMock server on port 8080.

  • Once the server is running, you can define your stubs. For example, let's say you want to create a mock endpoint for the URL http://localhost:8080/greeting. You can define a stub using the following code:
less
Copy code
import static com.github.tomakehurst.wiremock.client.WireMock.*; stubFor(get(urlEqualTo("/greeting")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/plain") .withBody("Hello, world!")));

This will create a stub that matches any HTTP GET request to the /greeting URL and returns a 200 status code with a plain text response of "Hello, world!".

  • Finally, you can use any HTTP client library to make requests to the mock service. For example, if you're using Java, you can use the Apache HttpClient library to make a request to the mock endpoint:
java
Copy code
import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClients; import org.apache.http.HttpResponse; import org.apache.http.util.EntityUtils; HttpClient httpClient = HttpClients.createDefault(); HttpGet request = new HttpGet("http://localhost:8080/greeting"); HttpResponse response = httpClient.execute(request); String responseBody = EntityUtils.toString(response.getEntity()); System.out.println(responseBody);

This will make a request to the http://localhost:8080/greeting endpoint and print the response body to the console. In this case, the response should be "Hello, world!".

These are the basic steps for using WireMock to create a mock HTTP service. You can create more complex stubs, such as those that return dynamic responses or simulate error conditions, by using WireMock's response templating and fault injection features.


    Leave a Comment


  • captcha text