解决使用WebTestClient访问接口报[185c31bb] 500 Server Error for HTTP GET “/**“

解决使用WebTestClient访问接口报[185c31bb] 500 Server Error for HTTP GET "/**"

问题发现

WebTestClientSpring WebFlux 框架中提供的用于测试 Web 请求的客户端工具。它可以不用启动服务器,模拟发送 HTTP 请求并验证服务器的响应。

在学习spring-test中,依照文档要求进行编写后报错,完整实例代码如下:

java 复制代码
@Controller
public class TestController {
    @GetMapping(value = "/test")
    public ResponseEntity<String> method(){
        return ResponseEntity.ok("Hello, world!");
    }
}
@WebFluxTest
public class MyServiceTest {
    @Test
    public void test() {
        WebTestClient webTestClient = WebTestClient.bindToController(new TestController())
                .configureClient()
                .build();
        WebTestClient.BodySpec<String, ?> response = webTestClient.get().uri("/test")
                .exchange()
                .expectStatus().isOk()//判断返回200
                .expectBody(String.class).isEqualTo("Hello, world!");//断言判断是否返回Hello, world!
    }
}

报错截图

由于没有启动服务看不到接受端到底是那个地方报错,因为这一个问题卡了三天之久,真的很难受!!!

问题解决

最开始包括,请求参数、返回参数、请求地址、请求方式、注解、等方面都检查(如果返回404更加要检查这些问题),发现都不是这些问题,最后尝试是不是依赖的版本导致的,结果成功解决。

原pom依赖代码:

xml 复制代码
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
            <version>2.0.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>2.4.0</version>
            <scope>test</scope>
        </dependency>

发现webflux的版本要低些,尝试改成一样的代码试试,改完以后的依赖代码:

xml 复制代码
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
            <version>2.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>2.4.0</version>
            <scope>test</scope>
        </dependency>

然后再次执行,结果如图:

接口请求成功!!!

网上对WebTestClient遇到的一些错误解决方案比较少,欢迎大家评论区交流。

相关推荐
毕设源码-赖学姐2 小时前
【开题答辩全过程】以 高校评教评学系统的设计与实现为例,包含答辩的问题和答案
java·eclipse
老华带你飞2 小时前
博物馆展览门户|基于Java博物馆展览门户系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·后端
路边草随风2 小时前
iceberg 基于 cosn 构建 catalog
java·大数据
It's now3 小时前
Spring Framework 7.0 原生弹性功能系统讲解
java·后端·spring
点PY3 小时前
C++ 中 std::async 和 std::future 的并发性
java·开发语言·c++
为爱停留3 小时前
Spring AI实现RAG(检索增强生成)详解与实践
人工智能·深度学习·spring
一 乐3 小时前
人事管理系统|基于Springboot+vue的企业人力资源管理系统设计与实现(源码+数据库+文档)
java·前端·javascript·数据库·vue.js·spring boot·后端
带刺的坐椅3 小时前
Solon AI 开发学习19 - 结合 Solon Flow 实现 ReAct 效果
java·ai·chatgpt·llm·openai·solon·deepseek
CoderYanger3 小时前
Java SE——12.异常(≠错误)《干货笔记》
java·开发语言
Data_agent3 小时前
1688获得1688店铺所有商品API,python请求示例
java·开发语言·python