How to mock remote REST API in unit test with Spring?

后端 未结 6 724
生来不讨喜
生来不讨喜 2020-12-14 00:49

Assume I have made a simple client in my application that uses a remote web service that is exposing a RESTful API at some URI /foo/bar/{baz}. Now I wish to uni

6条回答
  •  自闭症患者
    2020-12-14 01:14

    Best method is to use WireMock. Add the following dependencies:

        
            com.github.tomakehurst
            wiremock
            2.4.1
        
        
            org.igniterealtime.smack
            smack-core
            4.0.6
        
    

    Define and use the wiremock as shown below

    @Rule
    public WireMockRule wireMockRule = new WireMockRule(8089);
    
    String response ="Hello world";
    StubMapping responseValid = stubFor(get(urlEqualTo(url)).withHeader("Content-Type", equalTo("application/json"))
                .willReturn(aResponse().withStatus(200)
                        .withHeader("Content-Type", "application/json").withBody(response)));
    

提交回复
热议问题