【问题标题】:Testing classes that make use of Spring 5 WebClient测试使用 Spring 5 WebClient 的类
【发布时间】:2018-05-29 03:30:36
【问题描述】:

我们正在慢慢地将一些项目从使用旧的 RestTemplate 类迁移到新的 Spring 5 WebClient。作为其中的一部分,我们有一些现有的测试类,它们使用 Mockito 来验证给定的方法是否会使用模板向端点 X 发出 GET/POST/whatever。

鉴于 WebClient 的流畅界面,同样的模拟方法并不实用。我花了一些时间使用 WireMock,这很棒,但不幸的是,似乎有一个错误,有时 WireMock 测试会溢出或挂起,因此我正在考虑替代方案。

对于用于验证 Spring 的 WebClient 是否将预期调用作为 SUT 执行的一部分的框架或技术,是否有人有任何其他建议?

【问题讨论】:

  • 你知道这个错误到底是什么吗?你确定它是Wiremock本身吗?因为它是您的案例的好工具,恕我直言。
  • 我使用 Mockito 和 WebClient 为我编写的 API 编写测试,我认为这没有任何问题。你为什么不使用 mockito 呢?
  • @uneq95 - 你使用启用深度存根吗?从我最初使用 Mockito 的尝试来看,它似乎不能很好地使用 WebClient 的流畅界面。
  • @f1dave 我没用过深螺柱,我什至不知道它是什么。
  • @uneq95 可能会提供一个代码示例,说明您对存根所做的操作作为此问题的答案,因为这可能对我和其他有相同问题的人有所帮助。

标签: spring mockito spring-webflux wiremock


【解决方案1】:

Spring 实际上使用OkHttp MockWebServer 来测试 WebClient。

Spring's Example Integration Tests

您可以设置有序的模拟响应或将模拟响应映射到请求详细信息。

【讨论】:

    【解决方案2】:

    MockWebServer 听起来很酷。一个改编的例子是:

    @ExtendWith(MockitoExtension.class)
    class serviceImplTest {
    
        private ServiceImpl serviceImpl;
        public static MockWebServer mockWebServer;
    
        @BeforeAll
        static void setUp() throws IOException {
            mockWebServer = new MockWebServer();
            mockWebServer.start();
        }
        
        @AfterAll
        static void tearDown() throws IOException {
            mockWebServer.shutdown();
        }
    
        @BeforeEach
        void init() {
            String baseUrl = String.format("http://localhost:%s", mockWebServer.getPort());
            serviceImpl = new ServiceImpl(WebClient.builder(), baseUrl);
        }
    
        @Test
        @DisplayName("whatever")
        void methodName() {
            mockWebServer.enqueue(new MockResponse().addHeader("header", "abcde123")); //MockWebServer will respond with the queued stub.
            String header = serviceImpl.fetchHeader();
            assertThat(header).isEqualTo("abcde123");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-01-07
      • 1970-01-01
      • 2020-01-17
      • 1970-01-01
      • 2020-04-11
      • 2021-01-19
      • 2020-12-31
      • 1970-01-01
      • 2018-02-19
      相关资源
      最近更新 更多