3

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.

user51
  • 8,843
  • 21
  • 79
  • 158
Sundar
  • 85
  • 4
  • 10

2 Answers2

7

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>
  • Thanks mate! How do I create a stub using Java? I can only create using Json now Is there any way – JAY MEHTA Jun 04 '21 at 14:16
  • any working example on how mapping should be defined? in src/main/resource? – harshit2811 Aug 10 '21 at 12:48
  • @harshit2811 there is many examples of json file content in the wiremock site: http://wiremock.org/docs/stubbing/ Create the files in the folder .../resources/mappings and they will be available as from java classpath as is mentioned in the reply – Jan Nielsen Oct 07 '21 at 11:51
  • 1
    And I had to import: ` com.github.tomakehurst wiremock-jre8 ` – Jan Nielsen Oct 07 '21 at 12:15
-1

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";}
  }
}