一,背景,java
有時候會對相同的代碼結構作一樣的操做,不一樣的時對參數的設置數據和預期結果;有沒有好的辦法提取出來相同的代碼,提升代碼的可重用度,junit4中使用參數化設置,來處理此種場景;數組
二,代碼展現,函數
1,右鍵test/com.duo.util新建->junit Test Case測試
2,修改測試運行器(@RunWith(Parameterized.class))this
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,聲明變量存儲測試數據和預期值spa
4,測試多組數據,就須要聲明一個數組存放結果數據;爲測試類聲明返回值爲Collection公共靜態方法;code
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 }
三,總結blog
1,更改默認的測試運行器爲RunWith(Parameterized.class)input
2,聲明變量存儲預期值和測試數據it
3,聲明一個返回值爲Collection公共靜態方法,並使用@Parameters進行修飾
4,爲測試類聲明一個帶有參數的公共構造函數,並在其中爲之聲明變量賦值