如何将 MockWebServer 用于 webclient 的 Junit 测试用例? [英] How can I use MockWebServer for Junit test cases of webclient?

查看:80
本文介绍了如何将 MockWebServer 用于 webclient 的 Junit 测试用例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 spring-boot 应用程序,它使用 webclient 调用一些第三方 URL(比如 http://example.com/someUri)(我已经使用 application-dev.properties 来注入这个url 以实现松散耦合)并使用响应并在我的应用程序中使用它.

I have a spring-boot application which calls some third party URL (let's say http://example.com/someUri) using webclient(I have used application-dev.properties for injecting this url in my application to achieve loose coupling) and consumes the response and use it in my application.

这是我第一次为 webclient 编写测试用例.在那里我使用了@SprintBootTest.我发现有两种方法可以通过模拟 api 调用来测试我的 webclient 与第三方 Api 调用,并将其调用到我的本地 url(将使用 url(http://localhost:{portNumber}/someUri)来自我的测试属性文件:src/test/resources/application.properties) 它将提供一些 mockedResponse 以回报我的真实客户:

It's my first time when I am going to write test cases for webclient. and there I used @SprintBootTest. I found that there are two ways where I can test my webclient with third party Api call by mocking the api call and make it call to my local url(which will be using url(http://localhost:{portNumber}/someUri) from my testing properties file: src/test/resources/application.properties) where It will be giving some mockedResponse in return to my real client:

  1. 使用wiremock
  2. 使用MockWebServer

考虑以上代码以便更好地理解:

consider above code for better understanding:

@Service
Class SampleService{
    
@Value("${sample.url}")
private String sampleUrl;

public String dummyClient() {
    String sample =webClient.get()
            .uri(sampleUrl)
            .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
            .retrieve()
            .bodyToMono(String.class)
            .block();
    return sample;

    }
 }

application-dev.properties:

application-dev.properties:

sample.url:http://example.com/someUri

src/test/resources/application.properties:

src/test/resouces/application.properties:

http://localhost:8090/someUri

测试类:

@SpringBootTest
public class sampleTestingClass {

@Autowired
private SampleService sampleService;

@Value("${sample.url}")
private String sampleUrl;

    public static MockWebServer mockWebServer = new MockWebServer();

    @BeforeAll
    static void setUp() throws IOException {
        mockWebServer.start(8090);
    }

    @AfterAll
    static void tearUp() throws IOException {
        mockWebServer.close();
    }

 HttpUrl url = mockWebServer.url("/someUri");
       
        mockWebServer
                .enqueue(
                new MockResponse()
                .setResponseCode(200)
                .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                        .setBody("Sample Successful")); 

      
        String sample = sampleService.dummyClient();
        assertEquals(sample ,matches("Sample Successful"));
    } 
}

但是此代码不起作用.它给了我上述错误:

but this code isn't working. it's giving me above error:

java.lang.NullPointerException 

如果有人知道如何解决这个问题以使用模拟 Url 实现我的单元测试,那将非常有帮助?提前致谢!

It will be really helpful if anybody knows how this can be fixed to achieve my unit testing using mocked Url? Thanks in advance!

推荐答案

这是一个工作示例:

@Component
public class QuotesClient {

  private final WebClient webClient;

  public QuotesClient(WebClient.Builder builder, @Value("${client.baseUrl}") String baseUrl) {
    this.webClient = builder.baseUrl(baseUrl).build();
  }

  public JsonNode getData() {
    return this.webClient
      .get()
      .retrieve()
      .bodyToMono(JsonNode.class)
      .block();
  }
}

使用 WebClient.Builder 是可选的.

相应的测试如下所示:

class QuotesClientTest {

  private QuotesClient quotesClient;
  private MockWebServer server;

  @BeforeEach
  public void setup() {
    this.server = new MockWebServer();
    this.quotesClient = new QuotesClient(WebClient.builder(), server.url("/").toString());
  }

  @Test
  public void test() {

    server.enqueue(new MockResponse()
      .setStatus("HTTP/1.1 200")
      .setBody("{\"bar\":\"barbar\",\"foo\":\"foofoo\"}")
      .addHeader("Content-Type", "application/json"));

    JsonNode data = quotesClient.getData();
    assertNotNull(data);

    System.out.println(data);

  }

}

如果您正在使用 WireMock、Spring Boot 和 JUnit 5,查看链接指南.

If you are searching for a similar setup using WireMock, Spring Boot, and JUnit 5, take a look at the linked guide.

这篇关于如何将 MockWebServer 用于 webclient 的 Junit 测试用例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆