一,背景,
有時候會對相同的代碼結構做同樣的操作,不同的時對參數的設置數據和預期結果;有沒有好的辦法提取出來相同的代碼,提高代碼的可重用度,junit4中使用參數化設置,來處理此種場景;
二,代碼展示,
1,右鍵test/com.duo.util新建->junit Test Case
2,修改測試運行器(@RunWith(Parameterized.class))
1 package com.duo.util; 2 3 import static org.junit.Assert.*; 4 5 import org.junit.Test; 6 import org.junit.runner.RunWith; 7 import org.junit.runners.Parameterized; 8 9 10 @RunWith(Parameterized.class) 11 public class ParameterTest { 12 13 14 }
3,聲明變量存儲測試數據和預期值
4,測試多組數據,就需要聲明一個數組存放結果數據;為測試類聲明返回值為Collection公共靜態方法;
1 package com.duo.util; 2 3 import static org.junit.Assert.*; 4 5 import java.util.Arrays; 6 import java.util.Collection; 7 8 import org.junit.Test; 9 import org.junit.runner.RunWith; 10 import org.junit.runners.Parameterized; 11 import org.junit.runners.Parameterized.Parameters; 12 13 14 @RunWith(Parameterized.class) 15 public class ParameterTest { 16 int expected = 0; 17 int input1 = 0; 18 int input2 = 0; 19 20 @Parameters 21 public static Collection<Object[]> t(){ 22 return Arrays.asList(new Object[][]{{3,1,2},{4,2,2}}); 23 } 24 25 public ParameterTest(int expected, int input1, int input2){ 26 this.expected = expected; 27 this.input1 = input1; 28 this.input2 = input2; 29 } 30 31 @Test 32 public void testAdd(){ 33 assertEquals(expected, new Calculate().add(input1, input2)); 34 } 35 36 37 }
三,總結
1,更改默認的測試運行器為RunWith(Parameterized.class)
2,聲明變量存儲預期值和測試數據
3,聲明一個返回值為Collection公共靜態方法,並使用@Parameters進行修飾
4,為測試類聲明一個帶有參數的公共構造函數,並在其中為之聲明變量賦值