[英]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.