Sniffing Request and Response on Wiremock

Sniffing Request and Response on Wiremock


Often we use Wiremock on our test classes without knowing how the entire request or response looks like, well, mostly the requests since we can construct the response body from plain string. For that apparently Wiremock has a nice little request listener that can be utilised to print out all requests received by the Wiremock port:

Syntax:
  @Rule
  WireMockRule wmr = new WireMockRule(8888);


  @Before
  public void setUp() {

    wmr.addMockServiceRequestListener(new RequestListener() {

      @Override
      public void requestReceived(Request req, Response resp) {
        System.out.println("URL: " + req.getAbsoluteUrl());
        System.out.println("Req Body: " + req.getBodyAsString());
        System.out.println("Resp Code: " + resp.getStatus());
        System.out.println("Resp Body: " + resp.getBodyAsString());
      }
    });
  }


or the Java 8 way:
    wmr.addMockServiceRequestListener((req, resp) -> {
        System.out.println("URL: " + req.getAbsoluteUrl());
        System.out.println("Req Body: " + req.getBodyAsString());
        System.out.println("Resp Code: " + resp.getStatus());
        System.out.println("Resp Body: " + resp.getBodyAsString());
      }



Minimal Example:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class WireMockTest {

  @Rule
  public WireMockRule wmr = new WireMockRule(8888);


  @Before
  public void setUp() {

    wmr.addMockServiceRequestListener((req, resp) -> {
      System.out.println("URL: " + req.getAbsoluteUrl());
      System.out.println("Req Body: " + req.getBodyAsString());
      System.out.println("Resp Code: " + resp.getStatus());
      System.out.println("Resp Body: " + resp.getBodyAsString());
    });
  }


  @Autowired
  TestRestTemplate template;

  @Test
  public void test() {
    wmr.stubFor(post(urlEqualTo("/some/thing"))
        .willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("Hello world!")));

    template.postForObject("http://localhost:8888/some/thing", "Hello?", String.class);
  }
}

Output of Minimal Example:
URL: http://localhost:8888/some/thing
Req Body: Hello?
Resp Code: 200
Resp Body: Hello world!

Have fun sniffing!!

Comments

Popular posts from this blog

Spring Boot 2: Parallelism with Spring WebFlux

Cucumber + Junit5 + Localstack