WireMock: Verify payload sent to a mocked service in JUnit 5

This was not totally logical to me so I’ll write the solution down here for myself and anyone else that might have the same problem as me 🙂

The solution is to use the WireMock.verify function to setup a payload assertion.

Example (pseudo code):

import com.github.tomakehurst.wiremock.client.WireMock;
import com.niklasottosson.myApplication;
import org.junit.jupiter.api.Test;

import static com.github.tomakehurst.wiremock.client.WireMock.equalToXml;
import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;


public class MyApplicationIntegrationTest {

  @Test
  public void happyCaseTest() {

    String expected = "Hello Test";
    String myPath = "/mymockservice"

    // 1. Setup WireMock
    WireMock.stubFor(post(urlEqualTo(myPath))
       .willReturn(
             aResponse()
                   .withStatus(200)
                   .withHeader("Content-Type", "text/xml")
                   .withBody("Hello from mock service")));        

   // 2. Run system under test
   myApplication.start();        

   // 3. Verify payload sent to mock service
   WireMock.verify(
       postRequestedFor(urlEqualTo(myPath))
            .withRequestBody(equalToXml(expected))
    );
  }
}

1. Setup a WireMock stub for receiving calls from myApplication on a specific path
2. Start system under test, myApplication in this case
3. Verify that a call has been made to the path AND with a request payload matching our “expected” result. If this validates the payload is as “expected” 🙂

So in conclusion, WireMock is doing the assertion here, not our testing framework

Tested with WireMock v.3.1.0

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre lang="" line="" escaped="" cssfile="">

This site uses Akismet to reduce spam. Learn how your comment data is processed.