單元測試junit使用


1.maven依賴

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito2</artifactId>
    <version>2.0.2</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>2.0.2</version>
    <scope>test</scope>
</dependency>

2.方法介紹(junit)

(1)@BeforeClass:靜態方法,當前測試類加載前調用;

(2)@AfterClass:靜態方法,當前測試類回收前調用;

(3)@Before:每一次執行@Test修飾的測試方法前調用,常用於初始化;

(4)@After:每一次執行完@Test修飾的測試方法后調用;

(5)@Test:測試方法,每一個方法必須要有斷言,測試方法之間沒有依賴,能否獨立執行。

3.測試樣例

 待測代碼:

 1 public class Calculator {
 2     private int init;
 3     public Calculator(int init) {
 4         this.init = init;
 5     }
 6     public int add(int a,int b) {
 7         return init+a+b;
 8     }
 9 
10 
11 }

測試方法:

 1 import org.junit.Before;
 2 import org.junit.BeforeClass;
 3 import org.junit.Test;
 4 import static org.junit.Assert.*;
 5 
 6 public class CalculatorTest {
 7     private Calculator calculator;
 8     private static int init;
 9     @BeforeClass
10     public static void setup() {
11         init = 2;
12     }
13     @Before
14     public void setup_1() {
15         calculator = new Calculator(init);
16     }
17     @Test
18     public void add_返回setup_1函數初始化的值_returnTrue() {
19         assertEquals(6,calculator.add(1,3));
20     }
21 
22     @Test
23     public void add_返回setup_1函數初始化的值_returnFalse() {
24         assertFalse(7==calculator.add(1,3));
25     }
26 }

結果:

 

 

 測試通過。@BeforeClass修飾的方法賦初值,@Before修飾的方法初始化calculator對象,@Test修飾的方法進行測試,簡單可知,初始值為2,加上1加上3,結果為6;測試樣例1 assertEquals斷言滿足結果為6,正確;測試樣例2 assertFalse 斷言結果7與計算結果6比較不相等,為false,預取得的條件是false,測試通過。

4.powermock,對有static、native、private、final方法的類進行模擬。

在測試類前加上:

@RunWith(PowerMockRunner.class) // 告訴JUnit使用PowerMockRunner進行測試
@PrepareForTest({擁有靜態方法的類.class}) // 所有需要測試的類列在此處,適用於模擬final類或有final, private, static, native方法的類
@PowerMockIgnore("javax.management.*") //為了解決使用powermock后,提示classloader錯誤

在調用靜態方法之前:

PowerMockito.mockStatic(擁有靜態方法的類.class);
when(擁有靜態方法的類.靜態方法(any(參數1.class),any(參數2.class))).thenReturn("字符串");

然后調用靜態方法

擁有靜態方法的類.靜態方法(參數1,參數2),剛方法返回值為"字符串"。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM