準備工作
編輯器:idea(非必須)
maven依賴(創建springboot自己會有):
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
spring-boot-starter-test 是springboot 1.4.0版本後在創建時候就會自動引入的一個測試依賴,無需我們在手動引入junit依賴,非常方便
JUnit中的註解
註解 | 作用 |
---|---|
@BeforeClass | 針對所有測試,只執行一次,且必須爲static void |
@Before | 始化方法,執行當前測試類的每個測試方法前執行 |
@Test | 測試方法,在這裏可以測試期望異常和超時時間 |
@After | 釋放資源,執行當前測試類的每個測試方法後執行 |
@AfterClass | 針對所有測試,只執行一次,且必須爲static void |
@Ignore | 略的測試方法(只在測試類的時候生效,單獨執行該測試方法無效) |
@RunWith | 可以更改測試運行器 ,缺省值 org.junit.runner.Runner |
一個單元測試類執行順序爲:@BeforeClass –> @Before –> @Test –> @After –> @AfterClass
每一個測試方法的調用順序爲:@Before –> @Test –> @After
測試實戰:
- 如何生成測試類:
在idea要測試一個類只需要選中類名然後右鍵選中如圖:
ok完成即可!會生成相應的測試方法:
- 測試詳解:
package com.zou.sell.dao;
import com.zou.sell.dataobject.ProductCategory;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.List;
/**
* @Author: WH
* @Date: 2019/4/29 22:29
* @Version 1.0
*/
@RunWith(SpringRunner.class)
@SpringBootTest()
public class ProductCategoryRepositoryTest {
@Autowired
private ProductCategoryRepository repository;
@Test
public void findOneTest() {
ProductCategory productCategory = repository.findById(1).orElse(null);
}
//表示這是一個測試方法
@Test
public void saveTest1() {
ProductCategory productCategory = new ProductCategory();
productCategory = repository.findById(2).orElse(null);
productCategory.setCategoryType(10);
repository.save(productCategory);
}
@Test
//事務回滾,加入這個註解測試寫入數據的數據就不會寫入數據庫
@Transactional
public void saveTest() {
ProductCategory productCategory = new ProductCategory("女生最愛",5);
ProductCategory result = repository.save(productCategory);
//返回結果result如果不爲空返回true
Assert.assertNotNull(result);
// Assert.assertNotEquals(null, result);
}
@Test
public void findByCategoryTypeInTest() {
List<Integer> list = Arrays.asList(2,3,10);
List<ProductCategory> result = repository.findByCategoryTypeIn(list);
//返回結果result不爲result.size()不爲0則返回true
Assert.assertNotEquals(0, result.size());
}
}
補充說明:
Assert中的更多方法可以自己去了解:
可以看到加了 @Test註解的方法都可以單獨運行,如果要測試全部方法可以直接運行這個類
這是測試成功的標誌: