Search code examples
maven-failsafe-pluginintegration-testingmockserver

Mockserver maven plugin: init mockserver expectations from file


I'm using Mockserver maven plugin to mock some requests for integration tests.

My pom.xml looks like:

        ...

        <plugin>
            <groupId>org.mock-server</groupId>
            <artifactId>mockserver-maven-plugin</artifactId>
            <version>5.5.1</version>
            <configuration>
                <serverPort>1080</serverPort>
                <logLevel>DEBUG</logLevel>
                <initializationClass>com.mycompany.ExampleInitializationClass</initializationClass>
            </configuration>
            <executions>
                <execution>
                    <id>run-mockserver</id>
                    <phase>pre-integration-test</phase>
                    <goals>
                        <goal>start</goal>
                    </goals>
                </execution>
                <execution>
                    <id>stop-mockserver</id>
                    <phase>post-integration-test</phase>
                    <goals>
                        <goal>stop</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

        ...

Problem here is that I have to provide expectations using a class (com.mycompany.ExampleInitializationClass) and I want to provide expectations using a JSON file like described here:

http://www.mock-server.com/mock_server/initializing_expectations.html

I didn't find any way in the plugin configuration to initialize the Mockserver with the property:

-Dmockserver.initializationJsonPath

Is there any way to achieve that? Thanks in advance.


Solution

  • You just have to define initializationJson property specifying path to JSON file with expectations:

    <plugin>
        <groupId>org.mock-server</groupId>
        <artifactId>mockserver-maven-plugin</artifactId>
        <version>5.5.1</version>
        <configuration>
            <serverPort>1080</serverPort>
            <logLevel>DEBUG</logLevel>
            <initializationJson>expectations.json</initializationJson>
        </configuration>
        <executions>
            ...
        </executions>
    </plugin>
    

    The catch here is that the file path is relative to testClasspath directory (e.g. ${project.basedir}/target/test-classes/), so you have to copy the expectation file there. You may use e.g. maven-antrun-plugin for this (as below) or maven-resources-plugin.

    <plugin>
        <artifactId>maven-antrun-plugin</artifactId>
        <executions>
            <execution>
                <goals>
                    <goal>run</goal>
                </goals>
                <configuration>
                    <tasks>
                        <copy file="your/expectations.json" todir="${project.basedir}/target/test-classes/"/>
                    </tasks>
                </configuration>
            </execution>
        </executions>
    </plugin>