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.

到目前為止,每個(gè)練習(xí)的解決方案都是通過(guò)使用StepVerifier將定義的發(fā)布者傳遞到test來(lái)檢查的。

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.

此類(lèi)來(lái)自于reactor-test,能夠訂閱任何發(fā)布者(例如,F(xiàn)lux或Akka Stream),
然后斷言一組用戶定義的關(guān)于序列的期望。

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

如果觸發(fā)的任何事件與當(dāng)前預(yù)期不匹配,StepVerifier將生成一個(gè)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...).

您可以從靜態(tài)工廠方法create獲取StepVerifier的實(shí)例。它提供了一個(gè)DSL來(lái)設(shè)置數(shù)據(jù)部分的期望,
并以單個(gè)終端期望(完成、錯(cuò)誤、取消)結(jié)束。

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.

請(qǐng)注意,您必須始終調(diào)用verify()方法或verify結(jié)合終端期望的快捷方式之一(verifyComplete或verifyError),
例如.verifyErrorMessage(String)。否則,StepVerifier將不會(huì)訂閱您的序列,并且不會(huì)斷言任何內(nèi)容。
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.

在這些練習(xí)中,這些方法將Flux或Mono作為參數(shù),您需要測(cè)試其行為。您應(yīng)該創(chuàng)建一個(gè)使用
所述Flux/Mono的StepVerifier,描述對(duì)它的期望并進(jìn)行驗(yàn)證。

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.

讓我們驗(yàn)證傳遞給第一個(gè)測(cè)試方法的序列是否發(fā)出兩個(gè)特定元素"foo"和"bar",然后驗(yàn)證通量是否成功完成。
    // 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.

現(xiàn)在,讓我們執(zhí)行相同的測(cè)試,但驗(yàn)證是否在最后傳播了異常。
    // 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(...)):

讓我們嘗試創(chuàng)建一個(gè)StepVerifier,期望User.getUsername()。
有些期望可以通過(guò)檢查下一個(gè)值的Predicate謂詞來(lái)實(shí)現(xiàn),
甚至可以通過(guò)將下一個(gè)值傳遞給 類(lèi)似斷言的斷言庫(kù) 比如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.

在下一個(gè)測(cè)試中,我們將收到一個(gè)需要一些時(shí)間才能發(fā)射的Flux。正如您所料,測(cè)試將需要一些時(shí)間才能運(yùn)行。
    // 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!

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

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).

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

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.

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

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

為了讓運(yùn)算符選擇該調(diào)度器,您應(yīng)該在傳遞給withVirtualTime的lambda內(nèi)懶惰地構(gòu)建運(yùn)算符鏈。

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).

然后,您必須將時(shí)間推進(jìn)作為測(cè)試場(chǎng)景的一部分,方法是調(diào)用thenAwait(Duration)或expectNoEvent(Duration)。
前者只是使時(shí)鐘提前,而如果在提供的持續(xù)時(shí)間內(nèi)觸發(fā)任何意外事件,則后者會(huì)額外失?。ㄕ?qǐng)注意,
即使時(shí)鐘沒(méi)有提前,幾乎所有時(shí)間都至少會(huì)有一個(gè)“訂閱”事件,因此如果您要在之后立即使用expectNoEvent,
通常應(yīng)該在.withVirtualTime()后面放置一個(gè)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:

讓我們來(lái)嘗試這一點(diǎn),通過(guò)快速測(cè)試我們長(zhǎng)達(dá)一小時(shí)的發(fā)布者
    // 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();
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,506評(píng)論 19 139
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,817評(píng)論 0 10
  • 《閉上眼睛才能看清楚自己》這本書(shū)是香海禪寺主持賢宗法師的人生體悟,修行心得及講學(xué)錄,此書(shū)從六個(gè)章節(jié)講述了禪修是什么...
    宜均閱讀 10,322評(píng)論 1 25
  • 前言 Google Play應(yīng)用市場(chǎng)對(duì)于應(yīng)用的targetSdkVersion有了更為嚴(yán)格的要求。從 2018 年...
    申國(guó)駿閱讀 65,731評(píng)論 15 98
  • 本文轉(zhuǎn)載自微信公眾號(hào)“電子搬磚師”,原文鏈接 這篇文章會(huì)以特別形象通俗的方式講講什么是PID。 很多人看到網(wǎng)上寫(xiě)的...
    這個(gè)飛宏不太冷閱讀 7,180評(píng)論 2 15

友情鏈接更多精彩內(nèi)容