用JUnit4進行參數化測試
參數化測試是一個JUnit 3不具備的功能。
基本使用方法
@RunWith
當類被@RunWith注解修飾,或者類繼承了一個被該注解修飾的類,JUnit將會使用這個注解所指明的運行器(runner)來運行測試,而不是JUnit默認的運行器。
要進行參數化測試,需要在類上面指定如下的運行器:
@RunWith (Parameterized.class)
然后,在提供數據的方法上加上一個@Parameters注解,這個方法必須是靜態static的,並且返回一個集合Collection。
在測試類的構造方法中為各個參數賦值,(構造方法是由JUnit調用的),最后編寫測試類,它會根據參數的組數來運行測試多次。
文檔中的例子
Class Parameterized的文檔中有一個例子:
For example, to test a Fibonacci function, write:
@RunWith(Parameterized.class) public class FibonacciTest { @Parameters public static Collection data() { return Arrays.asList(new Object[][] { { 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } }); } private int fInput; private int fExpected; public FibonacciTest(int input, int expected) { fInput = input; fExpected = expected; } @Test public void test() { assertEquals(fExpected, Fibonacci.compute(fInput)); } }
參數化測試實例
還是以前面的Calculator類作為例子,進行參數化測試:
Calculator
package com.mengdd.junit4; public class Calculator { public int add(int a, int b) { return a + b; } public int subtract(int a, int b) { return a - b; } public int multiply(int a, int b) { return a * b; } public int divide(int a, int b) throws Exception { if (0 == b) { throw new Exception("除數不能為0"); } return a / b; } }
參數化測試加法的類:
package com.mengdd.junit4; import java.util.Arrays; import java.util.Collection; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) // 指定運行器runner:使用參數化運行器來運行 public class ParametersTest { private int expected;// 期待的結果值 private int input1;// 參數1 private int input2;// 參數2 private Calculator calculator = null; @Parameters public static Collection prepareData() { // 測試數據 Object[][] objects = { { 3, 1, 2 }, { -4, -1, -3 }, { 5, 2, 3 }, { 4, -4, 8 } }; return Arrays.asList(objects);// 將數組轉換成集合返回 } @Before public void setUp() { calculator = new Calculator(); } public ParametersTest(int expected, int input1, int input2) { // 構造方法 // JUnit會使用准備的測試數據傳給構造函數 this.expected = expected; this.input1 = input1; this.input2 = input2; } @Test public void testAdd() { Assert.assertEquals(this.expected, calculator.add(this.input1, this.input2)); } }
參考資料
聖思園張龍老師視頻教程。
JUnit4 chm格式文檔網盤下載鏈接:
JUnit 4.0:http://pan.baidu.com/share/link?shareid=539345&uk=2701745266
