# Junit # Junit 支援 Spring Boot的版本 | Spring Boot | Junit | | -------- | -------- | | <=2.1 | 4 | | 2.2、2.3 | 4、5 | | >=2.4 | 5 | # Junit 常使用的註解 | 常用註解 | 用途 | 註解 | | -------- | -------- | -------- | | @BeforeEach | 在每次@Test開始前,都會執行一次 || | @AfterEach | 在每次@Test結束後,都會執行一次 || | @BeforeAll | 在所有@Test開始前,都會執行一次 | 方法需要為static,無法使用到Spring Bean 故不常使用| | @AfterAll | 在所有@Test結束後,都會執行一次 | 方法需要為static,無法使用到Spring Bean 故不常使用| | @Disabled | 忽略該@Test不執行 || | @DisplayName | 自定義顯示名稱 || ```java= @BeforeEach public void beforeEach(){ System.out.println("執行@BeforeEach"); } @AfterEach public void AfterEach() { System.out.println("執行@AfterEach"); } @DisplayName("測試") @Test public void test() { } @Disabled @Test public void test1() { } ``` # Junit 常使用的方法 | Assert 用法 | 用途 | | -------- | -------- | | assertNull(A) | 斷言A為null | | assertNotNull(A) | 斷言A不為 | | assertEquals(A,B) | 斷言A和B相等,會使用equale()方法去判斷 | | assertTrue(A) | 斷言A為true | | assertFalse(A) | 斷言A為false | | assertThrows(exception,method) | 斷言執行method時,會跳出exception | ```java= @Test public void findByid() { CurrencyVo currencyVo =currencyService.findByid(1); assertEquals("USD", currencyVo.getCurrencyCode()); assertEquals("美元", currencyVo.getCurrencyName()); assertNotNull(currencyVo); } ``` # Spring Boot 使用Junit基本註解 | 註解 | 用途 | | -------- | -------- | | @SpringBootTest | 開始Test啟動Spring Boot,啟動Spring容器 | | @Transactional | 在單元測試結束後,rollBack 所有資料庫操作,將數據恢復(main時,發生錯誤才會rollBack) | ```java= @Transactional @SpringBootTest class XXXTest { @Autowired XXXService XXXService; @Test public void findByid() { XXXVo XXXVo =XXXService.findByid(1); assertEquals("USD", XXXVo.getCode()); assertEquals("美元", XXXVo.getName()); assertNotNull(XXXVo); } } ``` # MockMvc (未完成)