Run WireMock Server as a SpringBoot application

Viewed 6920

I am new to WireMock framework. My request is to run WireMock as a server that can accept stubs on a Spring Boot application. I tried to use the Spring Cloud Contract dependency but that only helps me in running the tests. Any direction or samples would be greatly helpful in this regard.

2 Answers

The main crux is to make the spring web-application-type: none in application.yml file. So that when the Spring Boot application is started from IDE it runs Wiremock on http port 8080 which internally runs on jetty server

Below is the appplication.yml file


    spring:
          main:
            web-application-type: none
          application:
            name: App
    wiremock:
          server:
            files: classpath:/__files
            stubs: classpath:/mappings

Below is SpringBoot Application class

 @SpringBootApplication
    @Slf4j
    @AutoConfigureWireMock()
    public class Application extends SpringBootServletInitializer {


        public static void main(String[] args) {
            log.info("Starting  Application");
            SpringApplication.run(Application.class, args);
        }



        @Bean
        public Options wireMockOptions() throws IOException {

            final WireMockConfiguration options = WireMockSpring.options();
            options.port(8080);

            return options;
        }



    }

Please make sure you have these dependencies

<dependency>
       <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-contract-wiremock</artifactId>
</dependency>
 <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-contract-wiremock</artifactId>
</dependency>

First, you have to add this dependency in your pom file to work with wire mock.

        <dependency>
            <groupId>com.github.tomakehurst</groupId>
            <artifactId>wiremock-standalone</artifactId>
            <version>2.19.0</version>
            <scope>test</scope>
       </dependency>

You need an initializer class to initialize the Class

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan({"your package name*"})
public class AppInitializer{
}

In this initializer, you can set various configurations, Then you have a base test class where you have the basic things which run in every test.

public abstract class AbstractTestBase {
    /* Constant(s): */
    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractTestBase.class);
    protected final static int HTTP_ENDPOINT_PORT = 8443;
    protected final static String CLIENT_ID = "user";
    protected final static String CLIENT_SECRET = "pass";
    protected static final int DEFAULT_TIMEOUT = 5000;
    protected WireMockServer mWireMockServer;

    /**
     * Performs preparations before each test.
     */

    @BeforeEach
    public void setup() {
        mWireMockServer = new WireMockServer(HTTP_ENDPOINT_PORT);
        mWireMockServer.start();
    }

    @AfterEach
    public void tearDown() {
        /* Stop the WireMock server. */
        mWireMockServer.stop();
    }
}

Then You may have the unit test classes for the wire mock

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {AppInitializer.class})
@ActiveProfiles("prod")
public class PhoneServiceUnitTest{
    @Autowired
    PhoneService phoneService;
   @Test
   public void callPhoneTest(){
      mWireMockServer.stubFor(get(urlEqualTo("phone/call"))
                     .withHeader(HttpHeaders.ACCEPT,
                     equalTo(MediaType.APPLICATION_JSON_VALUE))
                     .willReturn(
                                aResponse()
                                        .withStatus(200)
                                        .withHeader(HttpHeaders.CONTENT_TYPE, 
                             MediaType.APPLICATION_JSON_VALUE)
                                        .withBodyFile("phone-response.json")
                        )
        );
        String result = phoneService.call("siva");
       Assert.assertEquals(result,"Ok");

     }
}

My phone-response.json json file

{ 
  "data":"phone is called"
}

My PhoneService interface implementation

@Profile("dev")
Class PhoneServcieImp implements PhoneService{
     private String owner = "siva";
     public String call(String name){
     if(name.equals(owner){
         //It calls (phone/call)rest API and check the response if the response is 200 it will 
         //retrun "OK"
       return "OK";
    }  else{
       return "fail";}
  }
}
Related