如何对Spring boot WebClient做单元测试
1.概述
在Spring boot 推出WebClient客户端后,由于具有强大的异步执行能力和性能优势逐步替换SpringRestTemplate。
在下面的介绍中,我们将了解如何对使用WebClient调用API的服务进行单元测试。
2. Mocking
我们的测试中有两个主要的Mocking方式:
- 使用Mockito来模拟WebClient的行为
- 使用实际WebClient客户端发起请求,通过使用MockWebServer (okhttp)模拟被调用服务端
3. 使用Mockito框架
Mockito是最常见的Java模拟库。它擅长于为方法调用提供预定义的响应,但是在模拟Fluent API时就会遇到一些问题,这是因为在Fluent API中,许多对象在调用代码和模拟代码之间传递,导致代码可读性不高
例如,我们有一个EmployeeService类,它有一个getEmployeeById方法,可以使用WebClient通过HTTP获取数据:
public class EmployeeService {
public Mono<Employee> getEmployeeById(Integer employeeId) {
return webClient
.get()
.uri("http://localhost:8080/employee/{id}", employeeId)
.ret