How to use WireMock for unit testing

WireMock is a Java library used to simulate HTTP services, which can help developers write and run Test automation for unit testing. WireMock can run as an independent HTTP server, configure expected HTTP requests and responses, and record detailed information on executing requests. It can be used to simulate back-end services for independent Integration testing. Here are the common methods and Java sample code for WireMock: 1. Initialize and shut down WireMock server: import com.github.tomakehurst.wiremock.WireMockServer; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; WireMockServer wireMockServer; @Before public void setup() { wireMockServer = new WireMockServer(options().port(8080)); wireMockServer.start(); } @After public void tearDown() { wireMockServer.stop(); } 2. Create and match requests: import static com.github.tomakehurst.wiremock.client.WireMock.*; stubFor(get(urlEqualTo("/api/user")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\"username\": \"john\", \"email\": \"john@example.com\"}"))); The above code creates a stub of a GET request. When the URL of the request is "/api/user", the List of HTTP status codes 200 is returned, the Content Type is "application/json", and the response body is a JSON string. 3. Verify the call of the request: import static com.github.tomakehurst.wiremock.client.WireMock.*; verify(getRequestedFor(urlEqualTo("/api/user"))); The above code verifies whether there is a call with a GET request URL of "/api/user". 4. Set latency and response time: import static com.github.tomakehurst.wiremock.client.WireMock.*; stubFor(get(urlEqualTo("/api/user")) .willReturn(aResponse() .withStatus(200) . withFixedDelay (1000))// Set a delay of 1 second to return the response The above code causes a delay of 1 second before the request returns a response. 5. Set the criteria for request matching: import static com.github.tomakehurst.wiremock.client.WireMock.*; stubFor(get(urlMatching("/api/user.*")) .withQueryParam("id", equalTo("123")) .willReturn(aResponse() .withStatus(200))); The above code uses a regular expression to match the URL, and the requested parameter id must be equal to '123'. Maven Dependency: <dependency> <groupId>com.github.tomakehurst</groupId> <artifactId>wiremock</artifactId> <version>2.27.2</version> <scope>test</scope> </dependency> The above is an introduction to unit testing using WireMock and sample code for commonly used methods.