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í)的解決方案都是通過使用StepVerifier將定義的發(fā)布者傳遞到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,能夠訂閱任何發(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來設(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()。
有些期望可以通過檢查下一個(gè)值的Predicate謂詞來實(shí)現(xiàn),
甚至可以通過將下一個(gè)值傳遞給 類似斷言的斷言庫(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í),我們需要一種方法來加快速度,同時(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):
通過使用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í)鐘沒有提前,幾乎所有時(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:

讓我們來嘗試這一點(diǎn),通過快速測(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)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,460評(píng)論 6 538
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,067評(píng)論 3 423
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,467評(píng)論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,468評(píng)論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 72,184評(píng)論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,582評(píng)論 1 325
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,616評(píng)論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,794評(píng)論 0 289
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,343評(píng)論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 41,096評(píng)論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,291評(píng)論 1 371
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,863評(píng)論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,513評(píng)論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,941評(píng)論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,190評(píng)論 1 291
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 52,026評(píng)論 3 396
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,253評(píng)論 2 375

推薦閱讀更多精彩內(nèi)容

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