JUnit5 TestSuite替代
JUnit4具有TestSuite類來聚合多個測試。 這在JUnit 5中不可用。通常,通過套件中的一堆命名測試進行的測試發現有些糟透了。 但是,如果目標不是測試發現,而是不同測試類之間的資源共享,那么創建父對象是有意義的。
JUnit 5提供了@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(); private static MyDao dao; @BeforeAll static void beforeAll() { dao = createDaoFrom(DB); } @Test void daoFeatureOne() { assertThat(dao.find( "no data" )).isEmpty(); } }上面是一個測試,它在測試類的全局生命周期中啟動數據庫。 它將一個dao對象連接到它,并且可以有多個測試可以重用該dao 。
在理想情況下,我們可以為每個測試重置所有內容,但是數據庫是啟動的昂貴資源。 也許我們可以添加一些beforeEach和afterEach掛鉤來清理其數據,但是我們不想對數據庫進行退回。 每一次。 類似地,如果每次運行,我們的dao一些框架啟動成本可能是不希望的。
上面作為我們項目中的唯一測試是可以的,但是如果還有其他需要該數據庫的測試又該怎么辦呢?如果真的需要運行AGES呢?
JUnit 5中沒有套件
是不是很煩 如果我們可以做的話:
@JUnit5TestSuite // not real @Children ({MyDaoTest. class , MyOtherDaoTest. class }) @Testcontainers class MyTestSuite { @Container private static final DatabaseContainer DB = createDbContainer(); }那將是很棒的……但是這會給我們帶來一些問題:
- 我們如何確保子測試不在套件之外運行?
- 這些測試如何訪問`DB`對象?
套房的替代選擇
假設我們有一個靜態方法getDb在需要時提供數據庫。
現在,讓我們重寫原始的DaoTest以使用它,并使其抽象化,以便測試運行器不會將其拾取:
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(); } }現在我們可以在套件中運行部分測試,讓我們定義套件。 我們還使用@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 }缺點
由于類在彼此的靜態位上運行,因此存在產生混淆的風險。
每個嵌套類都必須是子類的事實也有點時髦……
但這有效并且構成了有效的測試套件。
翻譯自: https://www.javacodegeeks.com/2020/04/junit5-testsuite-alternative.html
總結
以上是生活随笔為你收集整理的JUnit5 TestSuite替代的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 谷歌拟 2027 年放弃博通,自主研发
- 下一篇: junit:junit_简而言之,JUn