單元測試-junit
引入依賴
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
在測試類中靜態引入 :
import static org.junit.Assert.*;
常用註解
- @BeforeClass: 針對所有測試,只執行一次,且必須爲static void
- @Before: 初始化方法,執行當前測試類的每個測試方法前執行。
- @Test: 測試方法,在這裏可以測試期望異常和超時時間
- @After: 釋放資源,執行當前測試類的每個測試方法後執行
- @AfterClass: 針對所有測試,只執行一次,且必須爲static void
- @Ignore: 忽略的測試方法(只在測試類的時候生效,單獨執行該測試方法無效)
- @RunWith: 可以更改測試運行器,缺省值 org.junit.runner.Runner
junit單元測試生命週期
@BeforeClass –> @Before –> @Test –> @After –> @AfterClass
常用斷言
- assertEquals
- assertNotEquals
- assertNull
- assertNotNull
- assertThrows