學習 Spring Boot:(二十九)Spring Boot Junit 單元測試
前言
JUnit 是一個迴歸測試框架,被開發者用於實施對應用程式的單元測試,加快程式編制速度,同時提高編碼的質量。
JUnit 測試框架具有以下重要特性:
- 測試工具
- 測試套件
- 測試執行器
- 測試分類
瞭解 Junit 基礎方法
加入依賴
在 pom.xml
中加入依賴:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
<version >4.12</version>
</dependency>
建立測試類和測試方法
- 測試類的的命名規則一般是
xxxTest.java
; - 測試類中測試的方法可以有字首,這個看統一標準,所以有時候會發現別人的測試方法上有
test
字首; - 並且測試方法上加上註解
@Test
。
使用 IDEA 中,選中當前類名,使用快捷鍵 ALT + ENTER
(WIN),向下選則 Create Test
回車,即可進入生成測試類的選項中,再次回車,就快速的生成測試類。
OK
完你會發現,生成的測試類在 src/test
目錄下,測試類和原始碼的包名 是一致的。生成後結果(注意下生成的方法名是不加 test):
public class HelloServiceImplTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void say() {
}
}
JUnit中的註解
@BeforeClass
:針對所有測試,只執行一次,且必須為static void
@Before
:初始化方法,執行當前測試類的每個測試方法前執行。@Test
@After
:釋放資源,執行當前測試類的每個測試方法後執行@AfterClass
:針對所有測試,只執行一次,且必須為static void
@Ignore
:忽略的測試方法(只在測試類的時候生效,單獨執行該測試方法無效)@RunWith
:可以更改測試執行器 ,預設值org.junit.runner.Runner
一個單元測試類執行順序為:
@BeforeClass
–> @Before
–> @Test
–> @After
–> @AfterClass
每一個測試方法的呼叫順序為:
@Before
–> @Test
–> @After
超時測試
如果一個測試用例比起指定的毫秒數花費了更多的時間,那麼 Junit 將自動將它標記為失敗。timeout
引數和 @Test
註釋一起使用。現在讓我們看看活動中的 @test(timeout)
。
@Test(timeout = 1000)
public void testTimeout() throws InterruptedException {
TimeUnit.SECONDS.sleep(2);
System.out.println("Complete");
}
上面測試會失敗,在一秒後會丟擲異常 org.junit.runners.model.TestTimedOutException: test timed out after 1000 milliseconds
異常測試
你可以測試程式碼是否它丟擲了想要得到的異常。expected 引數和 @Test 註釋一起使用。現在讓我們看看活動中的 @Test(expected)
。
@Test(expected = NullPointerException.class)
public void testNullException() {
throw new NullPointerException();
}
上面程式碼會測試成功。
套件測試
public class TaskOneTest {
@Test
public void test() {
System.out.println("Task one do.");
}
}
public class TaskTwoTest {
@Test
public void test() {
System.out.println("Task two do.");
}
}
public class TaskThreeTest {
@Test
public void test() {
System.out.println("Task Three.");
}
}
@RunWith(Suite.class) // 1. 更改測試執行方式為 Suite
// 2. 將測試類傳入進來
@Suite.SuiteClasses({TaskOneTest.class, TaskTwoTest.class, TaskThreeTest.class})
public class SuitTest {
/**
* 測試套件的入口類只是組織測試類一起進行測試,無任何測試方法,
*/
}
引數化測試
Junit 4 引入了一個新的功能引數化測試。引數化測試允許開發人員使用不同的值反覆運行同一個測試。你將遵循 5 個步驟來建立引數化測試。
- 用
@RunWith(Parameterized.class)
來註釋 test 類。 - 建立一個由
@Parameters
註釋的公共的靜態方法,它返回一個物件的集合(陣列)來作為測試資料集合。 - 建立一個公共的建構函式,它接受和一行測試資料相等同的東西。
- 為每一列測試資料建立一個例項變數。
- 用例項變數作為測試資料的來源來建立你的測試用例。
//1.更改預設的測試執行器為RunWith(Parameterized.class)
@RunWith(Parameterized.class)
public class ParameterTest {
// 2.宣告變數存放預期值和測試資料
private String firstName;
private String lastName;
//3.宣告一個返回值 為Collection的公共靜態方法,並使用@Parameters進行修飾
@Parameterized.Parameters //
public static List<Object[]> param() {
// 這裡我給出兩個測試用例
return Arrays.asList(new Object[][]{{"Mike", "Black"}, {"Cilcln", "Smith"}});
}
//4.為測試類宣告一個帶有引數的公共建構函式,並在其中為之宣告變數賦值
public ParameterTest(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// 5. 進行測試,發現它會將所有的測試用例測試一遍
@Test
public void test() {
String name = firstName + " " + lastName;
assertThat("Mike Black", is(name));
}
}
Hamcrest
JUnit 4.4 結合 Hamcrest 提供了一個全新的斷言語法——assertThat。
語法:
assertThat( [actual], [matcher expected] );
assertThat 使用了 Hamcrest 的 Matcher 匹配符,使用者可以使用匹配符規定的匹配準則精確的指定一些想設定滿足的條件,具有很強的易讀性,而且使用起來更加靈活。
具體使用的一些匹配規則可以檢視原始碼。
Spring Boot 中使用 JUnit
Spring 框架提供了一個專門的測試模組(spring-test),用於應用程式的整合測試。 在 Spring Boot 中,你可以通過spring-boot-starter-test啟動器快速開啟和使用它。
加入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
Spring Boot 測試
// 獲取啟動類,載入配置,確定裝載 Spring 程式的裝載方法,它回去尋找 主配置啟動類(被 @SpringBootApplication 註解的)
@SpringBootTest
// 讓 JUnit 執行 Spring 的測試環境, 獲得 Spring 環境的上下文的支援
@RunWith(SpringRunner.class)
public class EmployeeServiceImplTest {
// do
}
Spring MVC 測試
當你想對 Spring MVC
控制器編寫單元測試程式碼時,可以使用@WebMvcTest
註解。它提供了自配置的 MockMvc
,可以不需要完整啟動 HTTP
伺服器就可以快速測試 MVC 控制器
。
需要測試的 Controller:
@RestController @RequestMapping(value = "/emp", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public class EmployeeController { private final EmployeeService employeeService; @Autowired public EmployeeController(EmployeeService employeeService) { this.employeeService = employeeService; } @GetMapping public ResponseEntity<List<EmployeeResult>> listAll() { return ResponseEntity.ok(employeeService.findEmployee()); } }
編寫
MockMvc
的測試類:@RunWith(SpringRunner.class) @WebMvcTest(EmployeeController.class) public class EmployeeController2Test { @Autowired private MockMvc mvc; @MockBean private EmployeeService employeeService; public void setUp() { // 資料打樁,設定該方法返回的 body一直 是空的 Mockito.when(employeeService.findEmployee()).thenReturn(new ArrayList<>()); } @Test public void listAll() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/emp")) .andExpect(status().isOk()) // 期待返回狀態嗎碼200 // JsonPath expression https://github.com/jayway/JsonPath //.andExpect(jsonPath("$[1].name").exists()) // 這裡是期待返回值是陣列,並且第二個值的 name 存在,所以這裡測試是失敗的 .andDo(print()); // 列印返回的 http response 資訊 } }
使用
@WebMvcTest
註解時,只有一部分的 Bean 能夠被掃描得到,它們分別是:@Controller
@ControllerAdvice
@JsonComponent
Filter
WebMvcConfigurer
HandlerMethodArgumentResolver
其他常規的@Component
(包括@Service
、@Repository
等)Bean 則不會被載入到 Spring 測試環境上下文中。
所以我在上面使用了資料打樁,Mockito
在這篇文章最後一節。
我們也可以注入Spring 上下文的環境到 MockMvc 中,如下編寫
MockMvc
的測試類:@RunWith(SpringRunner.class) @SpringBootTest public class EmployeeControllerTest { /** * Interface to provide configuration for a web application. */ @Autowired private WebApplicationContext ctx; private MockMvc mockMvc; /** * 初始化 MVC 的環境 */ @Before public void before() { mockMvc = MockMvcBuilders.webAppContextSetup(ctx).build(); } @Test public void listAll() throws Exception { mockMvc .perform(get("/emp") // 測試的相對地址 .accept(MediaType.APPLICATION_JSON_UTF8) // accept response content type ) .andExpect(status().isOk()) // 期待返回狀態嗎碼200 // JsonPath expression https://github.com/jayway/JsonPath .andExpect(jsonPath("$[1].name").exists()) // 這裡是期待返回值是陣列,並且第二個值的 name 存在 .andDo(print()); // 列印返回的 http response 資訊 } }
值得注意的是需要首先使用
WebApplicationContext
構建MockMvc
。
Spring Boot Web 測試
當你想啟動一個完整的 HTTP 伺服器對 Spring Boot 的 Web 應用編寫測試程式碼時,可以使用@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
註解開啟一個隨機的可用埠。Spring Boot 針對 REST 呼叫的測試提供了一個 TestRestTemplate
模板,它可以解析連結伺服器的相對地址。
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class EmployeeController1Test {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void listAll() {
ResponseEntity<List> result = restTemplate.getForEntity("/emp", List.class);
Assert.assertThat(result.getBody(), Matchers.notNullValue());
}
}
其實之前上面的測試返回結果不是很正確,只能接收個List,給測試程式碼添加了不少麻煩,還好最終找到了解決辦法:
@Test
public void listAll() {
// 由於我返回的是 List 型別的,一直想不到辦法解決,網上給出瞭解決辦法,使用 exchange 函式代替
//public <T> ResponseEntity<T> exchange(String url, HttpMethod method,
// HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType,
// Object... urlVariables) throws RestClientException {
ParameterizedTypeReference<List<EmployeeResult>> type = new ParameterizedTypeReference<List<EmployeeResult>>() {};
ResponseEntity<List<EmployeeResult>> result = restTemplate.exchange("/emp", HttpMethod.GET, null, type);
Assert.assertThat(result.getBody().get(0).getName(), Matchers.notNullValue());
}
Spring Data JPA 測試
我們可以使用 @DataJpaTest
註解表示只對 JPA 測試;@DataJpaTest
註解它只掃描@Entity
Bean 和裝配 Spring Data JPA 儲存庫,其他常規的@Component
(包括@Service
、@Repository
等)Bean 則不會被載入到 Spring 測試環境上下文。
@DataJpaTest
還提供兩種測試方式:
- 使用記憶體資料庫
h2database
,Spring Data Jpa 測試預設採取的是這種方式; - 使用真實環境的資料庫。
使用記憶體資料庫測試
預設情況下,
@DataJpaTest
使用的是記憶體資料庫進行測試,你無需配置和啟用真實的資料庫。只需要在pom.xml
配置檔案中宣告如下依賴即可:<dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency>
gradle file:
testCompile('com.h2database:h2')
編寫測試方法:
@RunWith(SpringRunner.class) @DataJpaTest public class EmployeeDaoTest { @Autowired private EmployeeDao employeeDao; @Test public void testSave() { Employee employee = new Employee(); EmployeeDetail detail = new EmployeeDetail(); detail.setName("kronchan"); detail.setAge(24); employee.setDetail(detail); assertThat(detail.getName(), Matchers.is(employeeDao.save(employee).getDetail().getName()));; } }
使用真實資料庫測試
如要需要使用真實環境中的資料庫進行測試,需要替換掉預設規則,使用@AutoConfigureTestDatabase(replace = Replace.NONE)
註解:
@RunWith(SpringRunner.class)
@DataJpaTest
// 加入 AutoConfigureTestDatabase 註解
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class EmployeeDaoTest {
@Autowired
private EmployeeDao employeeDao;
@Test
public void testSave() {
Employee employee = new Employee();
EmployeeDetail detail = new EmployeeDetail();
detail.setName("kronchan");
detail.setAge(24);
employee.setDetail(detail);
assertThat(detail.getName(), Matchers.is(employeeDao.save(employee).getDetail().getName()));;
}
}
事務控制
執行上面的新增資料的測試,發現測試通過,但是資料庫卻並沒有新增資料。預設情況下,在每個 JPA 測試結束時,事務會發生回滾。這在一定程度上可以防止測試資料汙染資料庫。
如果你不希望事務發生回滾,你可以使用@Rollback(false)
註解,該註解可以標註在類級別做全域性的控制,也可以標註在某個特定不需要執行事務回滾的方法級別上。
也可以顯式的使用註解 @Transactional
設定事務和事務的控制級別,放大事務的範圍。
Mockito
JUnit
和SpringTest
,基本上可以滿足絕大多數的單元測試了,但是,由於現在的系統越來越複雜,相互之間的依賴越來越多。特別是微服務化以後的系統,往往一個模組的程式碼需要依賴幾個其他模組的東西。因此,在做單元測試的時候,往往很難構造出需要的依賴。一個單元測試,我們只關心一個小的功能,但是為了這個小的功能能跑起來,可能需要依賴一堆其他的東西,這就導致了單元測試無法進行。所以,我們就需要再測試過程中引入Mock
測試。
所謂的Mock
測試就是在測試過程中,對於一些不容易構造的、或者和這次單元測試無關但是上下文又有依賴的物件,用一個虛擬的物件(Mock物件)來模擬,以便單元測試能夠進行。
比如有一段程式碼的依賴為:
當我們要進行單元測試的時候,就需要給A
注入B
和C
,但是C
又依賴了D
,D
又依賴了E
。這就導致了,A的單元測試很難得進行。
但是,當我們使用了Mock來進行模擬物件後,我們就可以把這種依賴解耦,只關心A本身的測試,它所依賴的B和C,全部使用Mock出來的物件,並且給MockB
和MockC
指定一個明確的行為。就像這樣:
因此,當我們使用Mock後,對於那些難以構建的物件,就變成了個模擬物件,只需要提前的做Stubbing
(樁)即可,所謂做樁資料,也就是告訴Mock物件,當與之互動時執行何種行為過程。比如當呼叫B物件的b()方法時,我們期望返回一個true
,這就是一個設定樁資料的預期。
基礎
Spring Boot 中使用
上面的 Spring MVC 測試
中也使用到了 Mockito
,
spring-boot-starter-test
自帶了 mockito-core
。
基礎業務
@Entity
@Data
@NoArgsConstructor
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true, nullable = false, length = 50)
private String username;
private String password;
@CreationTimestamp
private Date createDate;
public User(Long id, String username) {
this.id = id;
this.username = username;
}
}
public interface IUserRepository extends JpaRepository<User, Long> {
boolean updateUser(User user);
}
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserServiceImpl implements IUserService {
private final IUserRepository userRepository;
@Override
public User findOne(Long id) {
return userRepository.getOne(id);
}
@Override
public boolean updateUsername(Long id, String username) {
User user = findOne(id);
if (user == null) {
return false;
}
user.setUsername(username);
return userRepository.updateUser(user);
}
}
測試類
public class IUserServiceTest {
private IUserService userService;
//@Mock
private IUserRepository userRepository;
@Before
public void setUp() throws Exception {
// 對所有註解了@Mock的物件進行模擬
// MockitoAnnotations.initMocks(this);
// 不使用註解,可以對單個物件進行 mock
userRepository = Mockito.mock(IUserRepository.class);
// 構造被測試物件
userService = new UserServiceImpl(userRepository);
// 打樁,構建當 userRepository的 getOne 函式執行引數為 1的時候,設定返回的結果 User
Mockito.when(userRepository.getOne(1L)).thenReturn(new User(1L, "kronchan"));
// 打樁,構建當 userRepository的 getOne 函式執行引數為 2的時候,設定返回的結果 null
Mockito.when(userRepository.getOne(2L)).thenReturn(null);
// 打樁,構建當 userRepository的 getOne 函式執行引數為 3的時候,設定結果丟擲異常
Mockito.when(userRepository.getOne(3L)).thenThrow(new IllegalArgumentException("The id is not support"));
// 打樁,當 userRepository.updateUser 執行任何User型別的引數,返回的結果都是true
Mockito.when(userRepository.updateUser(Mockito.any(User.class))).thenReturn(true);
}
@Test
public void testUpdateUsernameSuccess() {
long userId = 1L;
String newUsername = "new kronchan";
// 測試某個 service 的方法
boolean updated = userService.updateUsername(userId, newUsername);
// 檢查結果
Assert.assertThat(updated, Matchers.is(true));
// Verifies certain behavior <b>happened once</b>.
// mock物件一旦建立,就會自動記錄自己的互動行為。通過verify(mock).someMethod()方法,來驗證方法是否被呼叫。
// 驗證呼叫上面的service 方法後是否 userRepository.getOne(1L) 呼叫過,
Mockito.verify(userRepository).getOne(userId);
// 有條件可以測試下沒有被呼叫過的方法:
// Mockito.verify(userRepository).deleteById(userId);
// 則會測試失敗:
// Wanted but not invoked:
// userRepository.deleteById(1L);
// However, there were exactly 2 interactions with this mock:
// userRepository.getOne(1L);
// userRepository.updateUser(
// User(id=1, username=new kronchan, password=null, createDate=null)
// );
// updateUsername 函式中我們呼叫了已經打樁了的其他的函式,現在我們來驗證進入其他函式中的引數
//構造引數捕獲器,用於捕獲方法引數進行驗證
ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);
// 驗證updateUser方法是否被呼叫過,並且捕獲入參
Mockito.verify(userRepository).updateUser(userCaptor.capture());
// 獲取引數 updatedUser
User updatedUser = userCaptor.getValue();
// 驗證入參是否是預期的
Assert.assertThat(updatedUser.getUsername(), Matchers.is(newUsername));
//保證這個測試用例中所有被Mock的物件的相關方法都已經被Verify過了
Mockito.verifyNoMoreInteractions(userRepository);
// 如果有一個互動,但是我們沒有verify ,則會報錯,
// org.mockito.exceptions.verification.NoInteractionsWanted:
// No interactions wanted here:
// -> at com.wuwii.service.IUserServiceTest.testUpdateUsernameSuccess(IUserServiceTest.java:74)
// But found this interaction on mock 'iUserRepository':
// -> at com.wuwii.service.impl.UserServiceImpl.findOne(UserServiceImpl.java:21)
// ***
}
@Test
public void testUpdateUsernameFailed() {
long userId = 2L;
String newUsername = "new kronchan";
// 沒有經過 mock 的 updateUser 方法,它返回的是 false
boolean updated = userService.updateUsername(userId, newUsername);
Assert.assertThat(updated, Matchers.not(true));
//驗證userRepository的getOne(2L)這個方法是否被呼叫過,(這個是被測試過的,此步驟通過)
Mockito.verify(userRepository).getOne(2L);
// 驗證 userRepository 的 updateUser(null)這個方法是否被呼叫過,(這個沒有被測試過,此步驟不通過)
//Mockito.verify(userRepository).updateUser(null);
Mockito.verifyNoMoreInteractions(userRepository);
}
}
分析
建立MOCK的物件
我需要對 userService
進行測定,就需要模擬 userRepository
物件。
我在 setUp()
方法中,模擬物件並打樁。
模擬物件有兩種方式:
- 對註解了@Mock的物件進行模擬
MockitoAnnotations.initMocks(this);
- 對單個物件手動 mock :
userRepository = Mockito.mock(IUserRepository.class);
資料打樁,除了上面我程式碼上用的幾個方法,還有非常多的方法,具體可以在使用的時候看到,主要分下面幾種:
最基本的用法就是呼叫
when
以及thenReturn
方法了。他們的作用就是指定當我們呼叫被代理的物件的某一個方法以及引數的時候,返回什麼值。提供引數匹配器,靈活匹配引數。
any()
、any(Class<T> type)
、anyBoolean()
、anyByte()
、anyChar()
、anyInt()
、anyLong()
等等,它支援複雜的過濾,可以使用正則Mockito.matches(".*User$"))
,開頭結尾驗證endsWith(String suffix)
,startsWith(String prefix)
、判空驗證isNotNull()
isNull()
也還可以使用 argThat(ArgumentMatcher matcher),如:ArgumentMatcher
只有一個方法boolean matches(T argument);
傳入入參,返回一個boolean表示是否匹配。Mockito.argThat(argument -> argument.getUsername.length() > 6;
Mockito還提供了兩個表示行為的方法:
thenAnswer(Answer<?> answer);
、thenCallRealMethod();
,分別表示自定義處理呼叫後的行為,以及呼叫真實的方法。這兩個方法在有些測試用例中還是很有用的。對於同一個方法,Mockito可以是順序與次數關心的。也就是說可以實現同一個方法,第一次呼叫返回一個值,第二次呼叫返回一個值,甚至第三次呼叫丟擲異常等等。只需要連續的呼叫
thenXXXX
即可。如果為一個返回為Void的方法設定樁資料。上面的方法都是表示的是有返回值的方法,而由於一個方法沒有返回值,因此我們不能呼叫
when
方法(編譯器不允許)。因此,對於無返回值的方法,Mockito提供了一些列的doXXXXX
方法,比如:doAnswer(Answer answer)
、doNothing()
、doReturn(Object toBeReturned)
、doThrow(Class<? extends Throwable> toBeThrown)
、doCallRealMethod()
。他們的使用方法其實和上面的thenXXXX
是一樣的,但是when
方法傳入的是Mock的物件:/*對void的方法設定模擬*/ Mockito.doAnswer(invocationOnMock -> { System.out.println("進入了Mock"); return null; }).when(fileRecordDao).insert(Mockito.any());
當 Mockito 監視一個真實的物件的時候,我們也可以模擬這個物件的方法返回我們設定的期望值,
List spy = spy(new LinkedList()); List spy = spy(new LinkedList()); // IndexOutOfBoundsException (the list is yet empty) when(spy.get(0)).thenReturn("foo"); // You have to use doReturn() for stubbing doReturn("foo").when(spy).get(0);
when方法引數中
spy.get(0)
,呼叫的是真實list物件的get(0),這會產生IndexOutOfBoundsException
異常,所以這時需要用到doReturn
方法來設定返回值。
驗證測試方法的結果
使用斷言語句檢查結果。
驗證MOCK物件的呼叫
其實,在這裡我們如果只是驗證方法結果的正確的話,就非常簡單,但是,在複雜的方法呼叫堆疊中,往往可能出現結果正確,但是過程不正確的情況。比如,updateUserName
方法返回false是有兩種可能的,一種可能是使用者沒有找到,還有一種可能就是userRepository.updateUser(userPO)
返回false。因此,如果我們只是使用Assert.assertFalse(updated);
來驗證結果,可能就會忽略某些錯誤。
因此我在上面的測試中還需要驗證指定的方法
userRepository).getOne(userId);
是否執行過,而且我還使用了引數捕獲器,抓取中間的方法引數,用來驗證。提供了
verify(T mock, VerificationMode mode)
方法。VerificationMode
有很多作用,// 驗證指定方法 get(3) 沒有被呼叫 verify(mock, never()).get(3);
verifyZeroInteractions
和verifyNoMoreInteractions
驗證所有 mock 的方法是否都呼叫過了。