單元測試-PowerMockito的使用(2)-mock進階
前言
上篇講解了mock的簡單實用,初步瞭解了mock,今天我們來了解一下進階的使用方式。
一、Mock進階使用
1.測試方法
/**
* @version 1.0
* @Description 方法mockDemo
* @Author 殘冬十九
* @Date 2020/6/12
*/
public class MockStaticDemo {
@Resource
private StaticDemoTarget staticDemoTarget;
/**
* 加法,求兩數之和
*
* @param a 數值A
* @param b 數值B
* @return 兩數之和
*/
public int addition(int a, int b) {
return a + StaticDemoTarget.multiply(b);
}
/**
* 加法,獲取a和ab中最大值的和,new出來的對象
*
* @param a 數值A
* @param b 數值B
* @return 兩數之和
*/
public int sum(int a, int b) {
return a + new StaticDemoTarget().max(a, b);
}
/**
* 加法,獲取a和ab中最大值的和,引用的對象
*
* @param a 數值A
* @param b 數值B
* @return 兩數之和
*/
public int sumResource(int a, int b) {
return a + staticDemoTarget.max(a, b);
}
}
class StaticDemoTarget {
/**
* 乘法,將數值A乘以3並返回
*
* @param a 數值A
* @return 數值a乘以三之後的值
*/
public static int multiply(int a) {
return a * 3;
}
/**
* 獲取最大值
*
* @param a 數值A
* @param b 數值B
* @return 最大值
*/
public int max(int a, int b) {
return Math.max(a, b);
}
}
Mock方法
/**
* @version 1.0
* @Description mock實例
* @Author 殘冬十九
* @Date 2020/6/12
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({StaticDemoTarget.class, MockStaticDemo.class})
public class MockStaticDemoTest extends TestCase {
@InjectMocks
private MockStaticDemo mockStaticDemo;
@Mock
private StaticDemoTarget staticDemoTarget;
/**
* 靜態方法摸mock
*/
public void testAddition() {
//mock靜態類
mockStatic(StaticDemoTarget.class);
//如果使用了anyInt()的測試條件,就代表任何數據都可以滿足條件。返回5
when(StaticDemoTarget.multiply(anyInt())).thenReturn(5);
//下面進行斷言
Assert.assertEquals(6, mockStaticDemo.addition(1, 2));
System.out.println("testAddition結束");
}
/**
* new 出對象mock
*
* @throws Exception
*/
public void testSum() throws Exception {
//設置最大值方法返回10
when(staticDemoTarget.max(anyInt(), anyInt())).thenReturn(10);
whenNew(StaticDemoTarget.class).withNoArguments().thenReturn(staticDemoTarget);
//下面進行斷言
Assert.assertEquals(11, mockStaticDemo.sum(1, 2));
System.out.println("testSum結束");
}
/**
* 引用出來對象mock
*
* @throws Exception
*/
public void testSumResource() throws Exception {
// mock一個需要resource的對象
StaticDemoTarget staticDemoTarget = mock(StaticDemoTarget.class);
//將兌現賦值進去
Whitebox.setInternalState(mockStaticDemo, "staticDemoTarget", staticDemoTarget);
//設置最大值方法返回10
when(staticDemoTarget.max(anyInt(), anyInt())).thenReturn(10);
whenNew(StaticDemoTarget.class).withNoArguments().thenReturn(staticDemoTarget);
//下面進行斷言
Assert.assertEquals(11, mockStaticDemo.sumResource(1, 2));
System.out.println("testSumResource結束");
}
}
上圖中可以看出,我們有靜態方法,代碼中new出來的對象,還有引用的對象三種mock方式,這三種方法也是比較常用的方法。
需要注意的是PrepareForTest註解,需要mock靜態方法的時候。必須使用PrepareForTest註解,並且在註解後跟上需要mock靜態方法對應的靜態類。如果使用PrepareForTest註解,就一定要配套使用RunWith註解纔行。
InjectMocks註解是註解需要測試的類,其他mock對象都會直接注入到這個類中。
希望寫的文章對大家有幫助。