TestNG を使いましょう

簡単な例

ArrayListのテストケースを書いてみると、

import static org.testng.Assert.assertEquals;

import java.util.ArrayList;
import java.util.List;

import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class ListTest {

    private List<String> list;
    
    @BeforeClass
    public void beforeClass() {
        list = new ArrayList<String>();
    }
    
    @BeforeMethod
    public void beforeMethod() {
        list.add("item 1");
        list.add("item 2");
    }
    
    @Test
    public void testList() {
        assertEquals(list.get(0), "item 1");
    }
}

こんな感じ。JUnitと同じように違和感なく使えます。

アノテーションの説明はhttp://testng.org/doc/documentation-main.html#annotations

例外の発生をテストする

例外の発生をテストするには@Testアノテーションの属性で以下の様に指定する。

    @Test(expectedExceptions=IndexOutOfBoundsException.class)
    public void testListException() {
        list.get(3);
    }

データ駆動テスト

@DataProviderアノテーションで、テストメソッドの引数を与えられる
以下のようにすると、verifyDataメソッドに引数を変えながら様々なデータでテストできる

    @DataProvider(name = "test")
    public Object[][] createData() {
        return new Object[][] {
            { "Cedric", new Integer(3), "ric"  },
            { "Anne",   new Integer(0), "Anne" }, 
        };
    }

    @Test(dataProvider = "test")
    public void verifyData(String str, int begin, String expected) {
        assertEquals(str.substring(begin), expected);
    }