JUnit 測試

Junit 使用html

一、忽略測試方法。在使用@Test的方法上使用@Ignore,將不會對此方法進行測試java

二、測試套件數組

解決的問題:函數

一、對測試類進行統一測試,而沒必要在單獨測試類上一個一個進行測試。測試

使用JUnit的@RunWith以及@SuiteClassses註解,@SuiteClassses後面爲待測試類的數組ui

示例:this

@RunWith(Suite.class)
@Suite.SuiteClasses({UserTest.class})  --指定要測試的類
public class TestAll {

}

 

三、參數化測試spa

解決問題:對同一個方法使用不一樣的參數進行測試。.net

  1. 爲準備使用參數化測試的測試類指定特殊的運行器 org.junit.runners.Parameterized。
  2. 爲測試類聲明幾個變量,分別用於存放指望值和測試所用數據。
  3. 爲測試類聲明一個使用註解 org.junit.runners.Parameterized.Parameters 修飾的,返回值爲 java.util.Collection 的公共靜態方法,並在此方法中初始化全部須要測試的參數對。
  4. 爲測試類聲明一個帶有參數的公共構造函數,並在其中爲第二個環節中聲明的幾個變量賦值。
  5. 編寫測試方法,使用定義的變量做爲參數進行測試。

示例:code

package com.vrvwh.wh01.testSuit;

import com.vrvwh.wh01.controller.Calculator;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.Arrays;
import java.util.Collection;

/**
 * Created by Administrator on 2015/1/22.
 */
@RunWith(Parameterized.class)
public class ParameterTest {
    private long expected;
    private long input1;
    private long input2;

    public ParameterTest(int expected, int x, int y){
        this.expected = expected;
        this.input1 = x;
        this.input2 = y;
    }

    @Parameterized.Parameters
    public static Collection getData(){
        Object[][] object = {{3,1,2}, {0,0,0}, {-4,-1,-3}, {6,-3,9}};
        return Arrays.asList(object);
    }

    @Test
    public void testAdd(){
        Calculator calculator=new Calculator();
        long result=calculator.add(input1,input2);
        Assert.assertTrue(expected == result);

    }
}

注意:getData中object 數組數據順序必須與構造函數順序匹配

參考:http://www.ibm.com/developerworks/cn/java/j-lo-junit4/index.html

http://blog.csdn.net/longeremmy/article/details/9331721

相關文章
相關標籤/搜索