【问题标题】:Correct dependencies to use when using WebClient with Spring MVC将 WebClient 与 Spring MVC 一起使用时要使用的正确依赖项
【发布时间】:2021-04-12 07:05:27
【问题描述】:

我正在使用 Spring MVC 开发一些控制器。

我想编写一些场景集成测试,这将涉及调用我的应用程序的多个控制器。

通常我会在这些测试中使用RestTemplate,但文档指出:

请考虑使用 org.springframework.web.reactive.client.WebClient,它具有更现代的 API 并支持同步、异步和流式处理方案。

所以我想使用 WebClient 编写面向未来的代码。但我有几个问题:

  1. 此处应包含哪些依赖项?
 // (1) For Spring MVC:
 'org.springframework.boot:spring-boot-starter-web:2.4.1'
 // (2) For spring webflux
 'org.springframework.boot:spring-boot-starter-webflux:2.4.1'

问题是我没有包含太多(1)和(2)吗?是否有一个单独的依赖项,我应该专门包含它以访问 WebClient?还是将这两者都包含在内是最佳做法?

  1. 我应该使用 WebClient 还是 TestWebClient 编写测试?

鉴于我只想在我编写的集成测试中向我的服务器发出 HTTP 请求 - 我认为使用 WebClient 可以吗?还是更喜欢在这类测试中使用 TestWebClient ?最佳做法是什么?

【问题讨论】:

  • WebTestClient 包含类似于 WebClient 的请求方法。此外,它还包含检查响应状态、标头和正文的方法。您还可以将 AssertJ 等断言库与 WebTestClient 一起使用。 34codefactory.medium.com/…

标签: spring-boot spring-mvc spring-webclient


【解决方案1】:

已测试将使用 TestRestTemplate 的现有集成测试转换为使用 WebTestClient 的集成测试

package no.mycompany.myapp.user;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.reactive.server.WebTestClient;

@AutoConfigureWebTestClient
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class LoginControllerTest {

    @Autowired
    WebTestClient webTestClient;
        
    @Test
    public void postLogin_withoutUserCredentials_receiveUnauthorized() {
        webTestClient.post()
                .uri("/login")
                .exchange()
                .expectStatus().isUnauthorized();
    }
}

将此添加到 POM

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
        <scope>test</scope>
    </dependency>

以下内容已经在 POM 中

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

【讨论】:

  • 谢谢 - 这很好用。我想在 MVC 旁边使用 WebClient 需要整个 webflux 启动器。
  • @vab2048:很高兴听到。是的,只需从我的回答中删除&lt;scope&gt;test&lt;/scope&gt;。 BR
猜你喜欢
  • 2015-06-08
  • 1970-01-01
  • 2017-11-06
  • 1970-01-01
  • 2020-01-18
  • 2022-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多