JUnit4:多組數據的單元測試

轉載原文:http://www.cnblogs.com/mengdd/archive/2013/04/13/3019336.html


基本使用方法

  @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;

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));
    }

}
複製代碼


發佈了1 篇原創文章 · 獲贊 5 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章