在 JUnit 測試中斷言異常處理
在 JUnit 中,測試應拋出異常的程式碼需要乾淨簡潔的方法。雖然可以手動檢查異常,但這不是慣用的方式。
JUnit 5 和 4.13
在 JUnit 版本 5 和 4.13 中,您可以使用 @Test(expected = ExceptionClass.class) 註解關於測試方法。這期望拋出指定的異常。
範例:
@Test(expected = IndexOutOfBoundsException.class) public void testIndexOutOfBoundsException() { ArrayList emptyList = new ArrayList(); emptyList.get(0); }
AssertJ 和 Google-Truth
如果使用 AssertJ 或 Google-Truth等等庫,您可以使用他們的斷言需要驗證
AssertJ:
import static org.assertj.core.api.Assertions.assertThatThrownBy; @Test public void testFooThrowsIndexOutOfBoundsException() { assertThatThrownBy(() -> foo.doStuff()).isInstanceOf(IndexOutOfBoundsException.class); }
Google-Truth:
import static com.google.common.truth.Truth.assertThat; @Test public void testFooThrowsIndexOutOfBoundsException() { assertThat(assertThrows(IndexOutOfBoundsException.class, foo::doStuff)).isNotNull(); }
Google-Truth:
@Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testIndexOutOfBoundsException() { thrown.expect(IndexOutOfBoundsException.class); ArrayList emptyList = new ArrayList(); emptyList.get(0); }
import static org.junit.Assert.assertEquals; @Test public void testIndexOutOfBoundsException() { try { ArrayList emptyList = new ArrayList(); emptyList.get(0); fail("IndexOutOfBoundsException was expected"); } catch (IndexOutOfBoundsException e) { assertEquals(e.getClass(), IndexOutOfBoundsException.class); } }JUnit 在JUnit 版本小於或等於4.12,可以使用Rule或TryCatch來處理異常。 使用Rule:使用TryCatch:
以上是如何在 JUnit 測試中斷言異常處理?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

云计算显著提升了Java的平台独立性。1)Java代码编译为字节码,由JVM在不同操作系统上执行,确保跨平台运行。2)使用Docker和Kubernetes部署Java应用,提高可移植性和可扩展性。

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

容器化技術如Docker增強而非替代Java的平台獨立性。 1)確保跨環境的一致性,2)管理依賴性,包括特定JVM版本,3)簡化部署過程,使Java應用更具適應性和易管理性。

JRE是Java應用程序運行的環境,其作用是讓Java程序在不同操作系統上運行無需重新編譯。 JRE的工作原理包括JVM執行字節碼、類庫提供預定義類和方法、配置文件和資源文件設置運行環境。

JVM通過自動內存管理和垃圾回收確保Java程序高效運行。 1)內存分配:為新對像在堆中分配內存。 2)引用計數:跟踪對象引用,檢測垃圾。 3)垃圾回收:使用標記-清除、標記-整理或複制算法回收不再引用的對象。

在使用IntelliJIDEAUltimate版本啟動Spring...

在使用MyBatis-Plus或其他ORM框架進行數據庫操作時,經常需要根據實體類的屬性名構造查詢條件。如果每次都手動...


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

Dreamweaver CS6
視覺化網頁開發工具