Home » Java » java – Wiremock record and stub at the same time-Exceptionshub

java – Wiremock record and stub at the same time-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a service(A) that calls another service(B) which i am mocking with a Wiremock. What i want to do is have a test in which:

  1. If i am in recording mode record the calls A -> B and put them in a file
  2. If i am in non-recording mode capture the calls A -> B and compare them with the pre-recorded mocks(it’s like regression testing)

My current structure is
BMockRule.java

public class BMockRule extendsWireMockClassRule {


    public BMockRule(Options options) {
        super(options);
    }

    @Override
    protected void before() {
        super.before();
        this.stub();
    }

    @Override
    public void stub() {

        this.stubFor(requestMatching(request ->
                MatchResult.of(request.getUrl().contains("/request")))
                .willReturn(aResponse().withStatus(200))
        );
    }
}

And a inside my test it looks like

public class QuoteCachePublisherIntTest {
    @ClassRule
    public static DropwizardAppRule<MicroServiceConfiguration> rule =
            new DropwizardAppRule<>(
                    MicroServiceApplication.class,
                    resourceFilePath("test_config.yml"));

    private QuoteCachePublisher publisher;

    @ClassRule
    public static BasicWiremockClassRule serviceB =
            new BMockRule(options().port(5100)).withStatus(200);

    @Test
    public void test_Request() {

        if(record) {
            WireMock.startRecording("http://localhost:5100");
        } 

        publisher.publish(parameters);

        if(record) {
            SnapshotRecordResult recordedMappings = WireMock.stopRecording()
            <write-stubs-to-file>
        } else {
            SnapshotRecordResult recordedMappings = <read-stubs-from-file>
        }

        // verify statements that compare the actual calls vs the recorded mappings
    }

The thing is that when i do the recording, the stubbing doesn’t work.
Is there a simple way to do achieve this.

Thanks 🙂

How to&Answers: