Reactive - 04 - StepVerifier

翻譯自:https://tech.io/playgrounds/929/reactive-programming-with-reactor-3/StepVerifier

StepVerifier


Description


Until now, your solution for each exercise was checked by passing the Publisher
you defined to a test using a StepVerifier.

到目前為止,每個練習的解決方案都是通過使用StepVerifier將定義的發布者傳遞到test來檢查的。

This class from the reactor-test artifact is capable of subscribing to
any Publisher (eg. a Flux or an Akka Stream...) and then assert a set
of user-defined expectations with regard to the sequence.

此類來自于reactor-test,能夠訂閱任何發布者(例如,Flux或Akka Stream),
然后斷言一組用戶定義的關于序列的期望。

If any event is triggered that doesn't match the current expectation,
the StepVerifier will produce an AssertionError.

如果觸發的任何事件與當前預期不匹配,StepVerifier將生成一個AssertionError。

You can obtain an instance of StepVerifier from the static factory create.
It offers a DSL to set up expectations on the data part and finish with a
single terminal expectation (completion, error, cancellation...).

您可以從靜態工廠方法create獲取StepVerifier的實例。它提供了一個DSL來設置數據部分的期望,
并以單個終端期望(完成、錯誤、取消)結束。

Note that you must always call the verify() method or one of the shortcuts
that combine the terminal expectation and verify, like .verifyErrorMessage(String).
Otherwise the StepVerifier won't subscribe to your sequence and nothing will
be asserted.

請注意,您必須始終調用verify()方法或verify結合終端期望的快捷方式之一(verifyComplete或verifyError),
例如.verifyErrorMessage(String)。否則,StepVerifier將不會訂閱您的序列,并且不會斷言任何內容。
StepVerifier.create(T<Publisher>)
.{expectations...}.verify()

Practice


In these exercises, the methods get a Flux or Mono as a parameter and you'll
need to test its behavior. You should create a StepVerifier that uses said
Flux/Mono, describes expectations about it and verifies it.

在這些練習中,這些方法將Flux或Mono作為參數,您需要測試其行為。您應該創建一個使用
所述Flux/Mono的StepVerifier,描述對它的期望并進行驗證。

Let's verify the sequence passed to the first test method emits two specific elements,
"foo" and "bar", and that the Flux then completes successfully.

讓我們驗證傳遞給第一個測試方法的序列是否發出兩個特定元素"foo"和"bar",然后驗證通量是否成功完成。
    // Use StepVerifier to check that the flux parameter emits "foo" and "bar" elements then completes successfully.
    void expectFooBarComplete(Flux<String> flux) {
        StepVerifier.create(flux).expectNext("foo", "bar").verifyComplete();
    }

Now, let's do the same test but verifying that an exception is propagated at the end.

現在,讓我們執行相同的測試,但驗證是否在最后傳播了異常。
    // Use StepVerifier to check that the flux parameter emits "foo" and "bar" elements then a RuntimeException error.
    void expectFooBarError(Flux<String> flux) {
        StepVerifier.create(flux).expectNext("foo", "bar").verifyError(RuntimeException.class);
    }

Let's try to create a StepVerifier with an expectation on a User's
getUsername() getter. Some expectations can work by checking a Predicate
on the next value, or even by consuming the next value by passing it to
an assertion library like Assertions.assertThat(T) from AssertJ.
Try these lambda-based versions (for instance StepVerifier#assertNext
with a lambda using an AssertJ assertion like assertThat(...).isEqualTo(...)):

讓我們嘗試創建一個StepVerifier,期望User.getUsername()。
有些期望可以通過檢查下一個值的Predicate謂詞來實現,
甚至可以通過將下一個值傳遞給 類似斷言的斷言庫 比如AssertJ的assertThat(T)。
嘗試這些基于lambda的版本(例如StepVerifier#assertNext使用AssertJ斷言的lambda,
如assertThat(...).isEqualTo(...)
    // Use StepVerifier to check that the flux parameter emits a User with "swhite"username
    // and another one with "jpinkman" then completes successfully.
    void expectSkylerJesseComplete(Flux<User> flux) {
        StepVerifier.create(flux)
                .expectNextMatches(user -> user.getUsername().equals("swhite"))
                .assertNext(user -> Assertions.assertThat(user.getUsername()).isEqualToIgnoringCase("jpinkman"))
                .verifyComplete();
    }

On this next test we will receive a Flux which takes some time to emit.
As you can expect, the test will take some time to run.

在下一個測試中,我們將收到一個需要一些時間才能發射的Flux。正如您所料,測試將需要一些時間才能運行。
    // Expect 10 elements then complete and notice how long the test takes.
    void expect10Elements(Flux<Long> flux) {
        StepVerifier.create(flux).expectNextCount(10).verifyComplete();
    }

The next one is even worse: it emits 1 element per second,
completing only after having emitted 3600 of them!

下一個更糟糕:它每秒發射1個元素,只有在發射3600個元素后才能完成!

Since we don't want our tests to run for hours, we need a way to speed that
up while still being able to assert the data itself (eliminating the time factor).

由于我們不想讓測試運行數小時,我們需要一種方法來加快速度,同時仍然能夠斷言數據本身(消除時間因素)。

Fortunately, StepVerifier comes with a virtual time option:
by using StepVerifier.withVirtualTime(Supplier<Publisher>), the verifier
will temporarily replace default core Schedulers (the component that define
the execution context in Reactor). All these default Scheduler are replaced
by a single instance of a VirtualTimeScheduler, which has a virtual clock
that can be manipulated.

幸運的是,StepVerifier附帶了一個虛擬時間選項:
通過使用StepVerifier.withVirtualTime(Supplier<Publisher>),驗證器將臨時替換默認的
核心調度程序(定義反應堆中執行上下文的組件)。所有這些默認調度程序都被VirtualTimeScheduler
的單個實例取代,該實例具有一個可以操縱的虛擬時鐘。

In order for the operators to pick up that Scheduler, you should lazily build
your operator chain inside the lambda passed to withVirtualTime.

為了讓運算符選擇該調度器,您應該在傳遞給withVirtualTime的lambda內懶惰地構建運算符鏈。

You must then advance time as part of your test scenario, by calling either
thenAwait(Duration) or expectNoEvent(Duration). The former simply advances
the clock, while the later additionally fails if any unexpected event triggers
during the provided duration (note that almost all the time there will at least
be a "subscription" event even though the clock hasn't advanced, so you should
usually put a expectSubscription() after .withVirtualTime() if you're going
to use expectNoEvent right after).

然后,您必須將時間推進作為測試場景的一部分,方法是調用thenAwait(Duration)或expectNoEvent(Duration)。
前者只是使時鐘提前,而如果在提供的持續時間內觸發任何意外事件,則后者會額外失敗(請注意,
即使時鐘沒有提前,幾乎所有時間都至少會有一個“訂閱”事件,因此如果您要在之后立即使用expectNoEvent,
通常應該在.withVirtualTime()后面放置一個expectSubscription())。
StepVerifier.withVirtualTime(() -> Mono.delay(Duration.ofHours(3)))
            .expectSubscription()
            .expectNoEvent(Duration.ofHours(2))
            .thenAwait(Duration.ofHours(1))
            .expectNextCount(1)
            .expectComplete()
            .verify();

Let's try that by making a fast test of our hour-long publisher:

讓我們來嘗試這一點,通過快速測試我們長達一小時的發布者
    // Expect 3600 elements at intervals of 1 second, and verify quicker than 3600s
    // by manipulating virtual time thanks to StepVerifier#withVirtualTime, notice how long the test takes
    void expect3600Elements(Supplier<Flux<Long>> supplier) {
        StepVerifier.withVirtualTime(supplier).thenAwait(Duration.ofHours(1)).expectNextCount(3600).verifyComplete();
    }
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容