[英]How to test java.net.http (Java 11) requests BodyPublisher?
我正在嘗試測試使用新的 Java 11 java.net.http.HttpClient
代碼。
在我的生產代碼中,我有這樣的事情:
HttpClient httpClient = ... (gets injected)
HttpRequest request = HttpRequest.newBuilder().uri(URI.create("http://localhost:1234"))
.POST(HttpRequest.BodyPublishers.ofByteArray("example".getBytes()))
.build();
return httpClient.send(request, HttpResponse.BodyHandlers.ofByteArray());
在我的測試中,我模擬了HttpClient
並獲得了java.net.http.HttpRequest
。 如何獲取/測試其請求正文(= 我的"example"
)? 我可以調用request.bodyPublisher()
來獲取HttpRequest.BodyPublisher
,但后來我被卡住了。
jdk.internal.net.http.RequestPublishers.ByteArrayPublisher
(它實際上是),但它不會編譯,因為模塊沒有導出相應的包。HttpRequest.BodyPublisher
( .contentLength()
, .subscribe(subscriber)
)中的可用方法,但我想它們不可能。BodyPublisher
並使用.equals()
比較它們,但沒有真正的實現,所以比較總是錯誤的。如果您對處理程序中 body 的外觀感興趣,您可以在 HttpRequest.BodyPublisher Subscriber 的幫助下了解它。 我們調用subscription.request
以接收所有正文項目並收集它們。
我們的 custrom 訂戶:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Flow;
public class FlowSubscriber<T> implements Flow.Subscriber<T> {
private final CountDownLatch latch = new CountDownLatch(1);
private List<T> bodyItems = new ArrayList<>();
public List<T> getBodyItems() {
try {
this.latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return bodyItems;
}
@Override
public void onSubscribe(Flow.Subscription subscription) {
//Retrieve all parts
subscription.request(Long.MAX_VALUE);
}
@Override
public void onNext(T item) {
this.bodyItems.add(item);
}
@Override
public void onError(Throwable throwable) {
this.latch.countDown();
}
@Override
public void onComplete() {
this.latch.countDown();
}
}
測試中的用法:
@Test
public void test() {
byte[] expected = "example".getBytes();
HttpRequest.BodyPublisher bodyPublisher =
HttpRequest.BodyPublishers.ofByteArray(expected);
FlowSubscriber<ByteBuffer> flowSubscriber = new FlowSubscriber<>();
bodyPublisher.subscribe(flowSubscriber);
byte[] actual = flowSubscriber.getBodyItems().get(0).array();
Assert.assertArrayEquals(expected, actual);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.