Kushagra Kapoor
Kushagra Kapoor

Reputation: 71

Wiremock :How to read the stub from a file in wiremock?

Currently I am setting up request and response in my stub through my java code like below.

wireMockRule.stubFor(WireMock.get(WireMock.urlEqualTo("/abc/xyz"))
                .willReturn(WireMock.aResponse()
                        .withBody("Hey")
                        .withStatus(HttpStatus.OK.value())
                        .withHeader("Content-Type",
                                "application/text")));

I wish to know if there is a possibility that I define all the stub configuration in the json file like below and just read it in my java code.

{
  "request": {
    "method": "GET",
    "url": "/abc/xyz"
  },
  "response": {
    "status": 200,
    "jsonBody": {"Hey"},
    "headers": {
      "Content-Type": "application/test"
    }
  }
}

I read about mapping folder over many post. I am not sure what that is and how do I get it and how can it help in my use case?

Also, I read about body file name but that just helps with the response body while I wish to find a solution which helps with the whole stub from a file.

A working java example would be really helpful.

Upvotes: 5

Views: 15590

Answers (4)

Dj Mamana
Dj Mamana

Reputation: 384

This a solution based on previous responses that allows reading from file or classpath, useful when you to deploy de fat jar with the stubs embedded

This is how I embed a WireMock server into my SpringBoot application (using dependency : implementation 'org.wiremock.integrations:wiremock-spring-boot:3.2.0'

The server is started if condition is met: @ConditionalOnProperty(...) based on a property set to true or false

@Configuration
@ConfigureWireMock(
        name = "my-mock-service",
        portProperties = "mock.my-mock-service.port",
        baseUrlProperties = "mock.my-mock-service.url",
        filesUnderClasspath = "wiremock/my-mock-service", //this looks inside: /wiremock/my-mock-service/mappings
        usePortFromPredefinedPropertyIfFound = true
)
@ConditionalOnProperty(value = "mock.my-mock-service", havingValue = "true")
public class PrestamosWiremockConfig {

    @Bean
    WireMockServer wiremockPrestamos(ConfigurableApplicationContext context) throws IOException {
        WireMockServerCreator creator = new WireMockServerCreator("my-mock-service");
        ConfigureWireMock otions =  PrestamosWiremockConfig.class.getAnnotation(ConfigureWireMock.class);
        WireMockServer wireMockServer = creator.createWireMockServer(context, otions);


        WiremockUtil.loadStubs(wireMockServer, "classpath:/wiremock/my-mock-service/**/*.json"); //This is to load json files from classpath

        return wireMockServer;
    }
}

Bellow code is an utility class that makes wiremock to properly load json files embedded in the springboot jar

    public class WiremockUtil {

    public static void loadStubs(WireMockServer wireMockServer, String locationPattern) throws IOException {
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        Resource[] resource = resourcePatternResolver.getResources(locationPattern);

        for (Resource r: resource) {
            try {
                loadMappingsInto(wireMockServer, r);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    public static void loadMappingsInto(WireMockServer server, Resource r) {
        Path mappingsFile = null;

        try {
            final StubMappingCollection stubCollection = Json.read(r.getInputStream().readAllBytes(),
                    StubMappingCollection.class);
            stubCollection.getMappingOrMappings().forEach(mapping -> {
                mapping.setDirty(false);
                server.addStubMapping(mapping);
            });
        } catch (JsonException e) {
            throw new MappingFileException(mappingsFile.toString(), e.getErrors().first().getDetail());
        } catch (IOException e) {
            Exceptions.throwUnchecked(e);
        }
    }
}

Upvotes: 0

Krystian
Krystian

Reputation: 1

You also can also set custom path to stubs in this way (version 3.3.1):

@Test
public void anyTest(WireMockRuntimeInfo runtimeInfo) {
    final WireMock wireMock = runtimeInfo.getWireMock();
    wireMock.loadMappingsFrom(rootDir);
}

Upvotes: 0

Markus Ridziauskas
Markus Ridziauskas

Reputation: 439

Actually wiremock under the hood just reads the files and maps them to a POJO. This can be seen by looking through the library source code (JsonFileMappingsSource.loadMappingsInto).

So to achieve the same you can just do:

private static StubMappingCollection deserialize(String fileContent) {
    return com.github.tomakehurst.wiremock.common.Json.read(
        fileContent,
        StubMappingCollection.class);
}

Upvotes: 0

Alvaro C.
Alvaro C.

Reputation: 171

Stubs file (src/test/resources):

stubs file in src/test/resources

Content file (stub.json):

content stubs.json file

Upvotes: 2

Related Questions