[英]Spring Webflux Mockito - mock the response of a Webclient call
[英]Webflux Microservice Error on WebClient Call;
我正在嘗試使用 Java + Spring + WebFlux 開始反應式編程。
我創建了一個通過控制器生成Mono<Customer>
的微服務。
@RestController
@RequestMapping("/customers")
public class CustomerController {
@GetMapping("/{id}")
public Mono<Customer> customerById(@PathVariable String id){
return customerService.findById(id);
}
}
public class Customer {
public Customer(String id, String fullName) {
this.id = id;
this.fullName = fullName;
}
@Id
private String id;
@NotNull(message = "The name must not be null")
private String fullName;
private String email;
private String document;
}
而另一位微服務消耗這個單是上述類的副本,除了Spring Validation
注解。
關於生產者:
//Service Class
public Mono<Customer> findById(String id){
return Mono.just(new Customer(id, "Joseph"));
}
//Method on Controller
@RestController
@RequestMapping("v1/customers")
public class CustomerController {
@GetMapping("/{id}")
public Mono<Customer> customerById(@PathVariable String id){
return customerService.findById(id);
}
}
當我在Customer Producer
端點上打開瀏覽器時,我得到以下信息:
{
id: "123",
fullName: "Joseph",
email: null,
document: null
}
當我在Customer Consumer
端點上調用GET
時,我得到一個HTTPCode = 500
下面是Customer Consumer
上的服務層
private String BASE_URL = "http://localhost:8060/";
public Mono<Customer> findById(String id){
WebClient.Builder builder = WebClient.builder();
return builder
.baseUrl(BASE_URL)
.build()
.get()
.uri("customers/{id}", id)
.retrieve()
.bodyToMono(Customer.class);
}
我也嘗試刪除.baseUrl(BASE_URL)
並連接到.uri()
,但沒有成功。
我在消費者方面遇到的錯誤:
2019-12-01 22:21:45.910 ERROR 16788 --- [ctor-http-nio-2] a.w.r.e.AbstractErrorWebExceptionHandler : [1510eee8] 500 Server Error for HTTP GET "/v1/customers/123"
java.lang.NullPointerException: null at com.poc.controller.CustomerController.findById(CustomerController.java:19) ~[classes/:na]
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
|_ checkpoint ? HTTP GET "/v1/customers/123" [ExceptionHandlingWebHandler]
Stack trace:
at com.poc.webportal.controller.CustomerController.findById(CustomerController.java:19) ~[classes/:na]
PS :我知道 WebClient 應該在bean
,但是例如,我只是想在重構代碼之前使其工作。
這很尷尬,但我忘了在控制器上注入CustomerService
。
所以, Autowired
解決了這個問題..
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.