EclipseでJUnit

□準備
パッケージエクスプローラでプロジェクトを右クリック
→「Build Path」
→「Add Libraries...」
→「JUnit
JUnit library version「JUnit 4」
→プロジェクトに「JUnit 4」が追加される


□テストクラス作成

import static org.junit.Assert.*;
import org.junit.Test;

public class XxxTest {
	@Test
	public void add() {
		// テストコード
		assertEquals(/* 期待値 */, /* 処理で出した値 */);
	}
}


□実行
パッケージエクスプローラを選択状態にしてEclipseのメニュー「Run」
→「Run As」
→「JUnit Test」


□テストクラスの自動生成
パッケージエクスプローラでソースファイルを右クリック
→「New」
→「JUnit Test Case」
→作成したいアノテーションとテストメソッドを選択

アノテーション 意味
@BeforeClass テストを実行する前に1度だけ実行される
@AfterClass テストを実行した後に1度だけ実行される
@Before 各テストメソッドを実行する前に実行される
@After 各テストメソッドを実行した後に実行される


自動生成のコード

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class XxxTest {

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
	}

	@Before
	public void setUp() throws Exception {
	}

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void testXxxMethod() {	// ←ダイアログで選択したメソッドのテスト
		fail("Not yet implemented");
	}
}