簡體   English   中英

如何測試 java.net.http (Java 11) 請求 BodyPublisher?

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM