3 回答

TA貢獻(xiàn)1840條經(jīng)驗(yàn) 獲得超5個(gè)贊
使用 AssertJ,另一種選擇是使用returns
:
import static org.assertj.core.api.Assertions.from;
assertThat(product)
? ? .returns("Coat", from(Product::getName))
? ? .returns(true, from(Product::getAvailable))
? ? ?//
? ? ?// or without 'from()'
? ? ?//
? ? .returns(12, Product::getAmount)
? ? .returns(new BigDecimal("88.0"), Product::getPrice);
有點(diǎn)冗長(zhǎng),但我發(fā)現(xiàn)與extracting
/相比更容易閱讀contains
。
請(qǐng)注意,這from
只是一個(gè)可選的語(yǔ)法糖,以提高可讀性。
從 3.22.0 開始,doesNotReturn
也可用。這對(duì)于事先不知道預(yù)期值的非空字段很有用。
assertThat(product) ????.returns("Coat",?from(Product::getName)) ????.returns(true,?from(Product::getAvailable)) ????.doesNotReturn(42,?from(Product::getAmount)) ????.doesNotReturn(null,?from(Product::getPrice));

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超13個(gè)贊
使用 AssertJ 最接近的是:
assertThat(product).extracting("name", "available", "amount", "price") .containsExactly("Coat", true, 12, new BigDecimal("88.0"));
但我不喜歡用String
s 引用字段名稱,因?yàn)樗鼈冏鳛樽侄蚊Q的有效性僅在運(yùn)行時(shí)檢查(已知的反射問(wèn)題),并且這些String
s 也可能在我們從 IDE 執(zhí)行的重構(gòu)操作期間被錯(cuò)誤地更新。
雖然有點(diǎn)冗長(zhǎng),但我更喜歡:
assertThat(product).extracting(Product::getName, Product::getAvailable, Product::getAmount, Product::getPrice) .containsExactly("Coat", true, 12, new BigDecimal("88.0"));
您引用的 AssertJ 優(yōu)于 Hamcrest 的優(yōu)勢(shì)在于它非常流暢:因此在大多數(shù)情況下,您需要一次導(dǎo)入:import org.assertj.core.api.Assertions;
對(duì)于集合斷言,有時(shí)需要:org.assertj.core.groups.Tuple;
這里是 JUnit 5 或 4;這并不重要,因?yàn)閷?duì)于非常簡(jiǎn)單的情況,您只會(huì)將 JUnit 用作測(cè)試運(yùn)行程序,而讓 AssertJ 執(zhí)行斷言。
或者,或者,在 JUnit 5 世界中最好的方法是什么。
JUnit 5(作為第 4 個(gè)版本)不提供靈活流暢的斷言功能。因此,使用 JUnit 5 的最佳方式來(lái)做這件事必然會(huì)產(chǎn)生更多的樣板代碼:與要斷言的字段一樣多的斷言或出于公平原因equals()/hashCode()
要避免的重寫。

TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超8個(gè)贊
你可以使用Assertions.assertAll:
assertAll("product",
? ?() -> assertEquals("Coat", product.getName()),
? ?() -> assertTrue(product.isAvaikable())
);
assertAll 可以接受任意多的單獨(dú)斷言。
添加回答
舉報(bào)