JUnit5 TestSuite替代
JUnit4具有TestSuite類來聚合多個(gè)測(cè)試。 這在JUnit 5中不可用。通常,通過套件中的一堆命名測(cè)試進(jìn)行的測(cè)試發(fā)現(xiàn)有些糟透了。 但是,如果目標(biāo)不是測(cè)試發(fā)現(xiàn),而是不同測(cè)試類之間的資源共享,那么創(chuàng)建父對(duì)象是有意義的。
JUnit 5提供了@Nested批注,以允許子類在其父類的上下文中運(yùn)行。 假定子類是非靜態(tài)的,因此可以訪問其父類的實(shí)例值。 如果要共享測(cè)試資源,則可能需要考慮測(cè)試套件的類級(jí)別設(shè)置,并以某種方式將其連接到子類的類級(jí)別設(shè)置中。
讓我們?cè)O(shè)計(jì)一個(gè)偽造的例子來說明問題:
@Testcontainers // use docker images @Testcontainers // use docker images class MyTest { // make a DB at the start of the test in a docker container // takes a few minutes to boot up @Container private static final DatabaseContainer DB = createDbContainer(); private static MyDao dao; @BeforeAll static void beforeAll() { dao = createDaoFrom(DB); } @Test void daoFeatureOne() { assertThat(dao.find( "no data" )).isEmpty(); } }上面是一個(gè)測(cè)試,它在測(cè)試類的全局生命周期中啟動(dòng)數(shù)據(jù)庫。 它將一個(gè)dao對(duì)象連接到它,并且可以有多個(gè)測(cè)試可以重用該dao 。
在理想情況下,我們可以為每個(gè)測(cè)試重置所有內(nèi)容,但是數(shù)據(jù)庫是啟動(dòng)的昂貴資源。 也許我們可以添加一些beforeEach和afterEach掛鉤來清理其數(shù)據(jù),但是我們不想對(duì)數(shù)據(jù)庫進(jìn)行退回。 每一次。 類似地,如果每次運(yùn)行,我們的dao一些框架啟動(dòng)成本可能是不希望的。
上面作為我們項(xiàng)目中的唯一測(cè)試是可以的,但是如果還有其他需要該數(shù)據(jù)庫的測(cè)試又該怎么辦呢?如果真的需要運(yùn)行AGES呢?
JUnit 5中沒有套件
是不是很煩 如果我們可以做的話:
@JUnit5TestSuite // not real @Children ({MyDaoTest. class , MyOtherDaoTest. class }) @Testcontainers class MyTestSuite { @Container private static final DatabaseContainer DB = createDbContainer(); }那將是很棒的……但是這會(huì)給我們帶來一些問題:
- 我們?nèi)绾未_保子測(cè)試不在套件之外運(yùn)行?
- 這些測(cè)試如何訪問`DB`對(duì)象?
套房的替代選擇
假設(shè)我們有一個(gè)靜態(tài)方法getDb在需要時(shí)提供數(shù)據(jù)庫。
現(xiàn)在,讓我們重寫原始的DaoTest以使用它,并使其抽象化,以便測(cè)試運(yùn)行器不會(huì)將其拾取:
abstract class MyTestImpl implements DbProvider { private static MyDao dao; @BeforeAll static void beforeAll() { // access to the database container // from the static method (statically imported) dao = createDaoFrom(getDb()); } @Test void daoFeatureOne() { assertThat(dao.find( "no data" )).isEmpty(); } }現(xiàn)在我們可以在套件中運(yùn)行部分測(cè)試,讓我們定義套件。 我們還使用@Nested來插入子類:
@Testcontainers // use docker images @Testcontainers // use docker images class MyTest { // make a DB at the start of the test in a docker container // takes a few minutes to boot up @Container private static final DatabaseContainer DB = createDbContainer(); // provide the getDb function to access the container public static DatabaseContainer getDb() { return DB; } // test suite members are just nested classes that extend // the abstract class of each member of the suite @Nested class MyTest extends MyTestImpl { } // ... add more suite members with more @Nested }缺點(diǎn)
由于類在彼此的靜態(tài)位上運(yùn)行,因此存在產(chǎn)生混淆的風(fēng)險(xiǎn)。
每個(gè)嵌套類都必須是子類的事實(shí)也有點(diǎn)時(shí)髦……
但這有效并且構(gòu)成了有效的測(cè)試套件。
翻譯自: https://www.javacodegeeks.com/2020/04/junit5-testsuite-alternative.html
總結(jié)
以上是生活随笔為你收集整理的JUnit5 TestSuite替代的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 谷歌拟 2027 年放弃博通,自主研发
- 下一篇: 小米卢伟冰:Redmi Note 系列手