【SpringBoot】Junit單元測試簡單入門

talk is cheap, show me the code.

SpringBoot 測試依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

基礎使用

  • 不需依賴 Spring 環境
public class TestAES {

    @Test
    public void encrypt() {
        String token = "yJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9";
        AES aes = new AES();
        Assert.assertEquals(token, aes.decode(aes.encode(token)));
    }
    
}
  • 依賴 Spring 環境
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestHello {

	@Autowire
	private HelloService helloService;
	
    @Test
    public void hello() {
        Assert.assertEquals("hello tanpeng", helloServic.sayHi());
    }
    
}

註解說明

  • 註解列表
    • @RunWith 標識爲JUnit的運行環境
    • @SpringBootTest 獲取啓動類、加載配置,確定裝載Spring Boot
    • @Test 聲明需要測試的方法
    • @BeforeClass 針對所有測試,只執行一次,且必須爲static void
    • @AfterClass 針對所有測試,只執行一次,且必須爲static void
    • @Before 每個測試方法前都會執行的方法
    • @After 每個測試方法前都會執行的方法
    • @Ignore 忽略方法
  • 超時測試
    • @Test(timeout = 1000) Test設置timeout屬性即可,時間單位爲毫秒

斷言測試

斷言測試也就是期望值測試,是單元測試的核心也就是決定測試結果的表達式

Assert對象中的斷言方法

  • Assert.assertEquals 對比兩個值相等
  • Assert.assertNotEquals 對比兩個值不相等
  • Assert.assertSame 對比兩個對象的引用相等
  • Assert.assertArrayEquals 對比兩個數組相等
  • Assert.assertTrue 驗證返回是否爲真
  • Assert.assertFlase 驗證返回是否爲假
  • Assert.assertNull 驗證null
  • Assert.assertNotNull 驗證非null
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章