この文書は、JUnit 4.0に含まれるcookbook.htmというドキュメントの勝手翻訳です。
(2006/02/21現在: 本家では4.0のドキュメントはまだ公開されていないようです)。

ダウンロードして中に入っていたファイルを翻訳しました。

日本語訳に誤りがある可能性があります。翻訳の正確性は保証しませんので、自己責任においてご使用下さい。

間違い等あれば、こちらにトラックバックをお願いします。

JUnit Cookbook

Kent Beck, Erich Gamma



Here is a short cookbook showing you the steps you can follow in writing and organizing your own tests using JUnit.
本書は、JUnitを使用してテストを作成、構成する際に従うステップを示す短い説明書です。

Simple Test Case

単純なテストケース

How do you write testing code?
どのようにテストコードを書いていますか?

The simplest way is as an expression in a debugger. You can change debug expressions without recompiling, and you can wait to decide what to write until you have seen the running objects. You can also write test expressions as statements which print to the standard output stream. Both styles of tests are limited because they require human judgment to analyze their results. Also, they don't compose nicely- you can only execute one debug expression at a time and a program with too many print statements causes the dreaded "Scroll Blindness".

最も単純な方法は、デバッガ内の式のようなものがあります。リコンパイル無しにデバッグの式を変更でき、動作しているオブジェクトを見ている間書き込みを待つことができます。標準出力に出力するステートメントとしてテストの式を書くこともできます。上記2つのテスト方法は結果を分析するために人間の判断が必要になるという制限があります。また、これらの方法はうまく組み立てられません、というのは、1度にひとつのデバッグの式しか実行せず、たくさんのprint文を持つプログラムは恐ろしい"Scroll Blindness"(訳注: 盲目にスクロールする。転じて、情報が多すぎるために人が重要な情報を見落としている状態を指す)を引き起こすからです。

JUnit tests do not require human judgment to interpret, and it is easy to run many of them at the same time. When you need to test something, here is what you do:

JUnitのテストは、結果を解釈するために人間の判断を 必要とせず、また同時に多くのテストを実行することを容易にします。テストが必要な時は次のようにします:
  1. Annotate a method with @org.junit.Test
    メソッドに@org.junit.Testの注釈(アノテーション)を加えます
  2. When you want to check a value, import org.junit.Assert.* statically, call assertTrue() and pass a boolean that is true if the test succeeds
    値をチェックしたい時は、org.junit.Assert.*を静的に(static)インポートし、assertTrue()を呼び出し、テストが成功した時はtrueとなる真偽値を渡します
For example, to test that the sum of two Moneys with the same currency contains a value which is the sum of the values of the two Moneys, write:
例えば、同じ通貨である2つのMoneyクラスの合計が、2つのMoneyクラスが持つ値の合計を含んでいるかをテストするには、次のように書いて下さい:
@Test public void simpleAdd() {
    Money m12CHF= new Money(12, "CHF"); 
    Money m14CHF= new Money(14, "CHF"); 
    Money expected= new Money(26, "CHF"); 
    Money result= m12CHF.add(m14CHF); 
    assertTrue(expected.equals(result));
}
If you want to write a test similar to one you have already written, write a Fixture instead.
今まで書いてきたテストに近いテストを書きたい場合は、 代わりに付属品(Fixture)の章にある方法で書いて下さい。

Fixture

付属品

What if you have two or more tests that operate on the same or similar sets of objects?
同じかあるいは似たオブジェクトの組み合わせの処理を行う2つ以上のテストがあったとしたらどうなるでしょうか?

Tests need to run against the background of a known set of objects. This set of objects is called a test fixture. When you are writing tests you will often find that you spend more time writing the code to set up the fixture than you do in actually testing values.

テストは周知のオブジェクトの組み合わせを背景に実行する必要があります。このオブジェクトの組み合わせはテストの付属品(test fixture)と呼ばれます。テストを書くとき、実際に値をテストするよりも、付属品をセットアップするためのコードを書くことに、より多くの時間を費やしていることにしばしば気づくでしょう。

To some extent, you can make writing the fixture code easier by paying careful attention to the constructors you write. However, a much bigger savings comes from sharing fixture code. Often, you will be able to use the same fixture for several different tests. Each case will send slightly different messages or parameters to the fixture and will check for different results.

作成するコンストラクタに細心の注意を払うことである程度楽に付属品を書けるようになります。しかし、より大きな節約は付属品のコードを共有することによってもたらされます。多くの場合、同じ付属品をいくつかの異なるテストに使用できるでしょう。それぞれのケースは、わずかに異なるメッセージや引数を付属品に渡し、かつ異なる結果をチェックするでしょう。

When you have a common fixture, here is what you do:

共有の付属品があれば、次のようにします:
  1. Add a field for each part of the fixture
    付属品の各部分にフィールドを加えます
  2. Annotate a method with @org.junit.Before and initialize the variables in that method
    メソッドに@org.junit.Beforeの注釈(アノテーション)を加え、メソッド内で値を初期化します
  3. Annotate a method with @org.junit.After to release any permanent resources you allocated in setUp
    セットアップで割り当てたいくつかの永続的なリソースを解放するために、メソッドに@org.junit.Afterの注釈(アノテーション)を加えます
For example, to write several test cases that want to work with different combinations of 12 Swiss Francs, 14 Swiss Francs, and 28 US Dollars, first create a fixture:
例えば、12スイスフラン、14スイスフラン、そして28USドルの異なる組み合わせを計算する、いくつかのテストケースを書くには、最初に次のような付属品を作成する:
public class MoneyTest { 
    private Money f12CHF; 
    private Money f14CHF; 
    private Money f28USD; 
    
    @Before public void setUp() { 
        f12CHF= new Money(12, "CHF"); 
        f14CHF= new Money(14, "CHF"); 
        f28USD= new Money(28, "USD"); 
    }
}
Once you have the Fixture in place, you can write as many Test Cases as you'd like. Add as many test methods (annotated with @Test) as you'd like.
一度適切な付属品を作成すれば、好きなだけ多くのテストケースに書くことができます。好きなだけ多くの(@Testで注釈を付けた)メソッドに追加することができます。

TestRunner

テストランナー

How do you run your tests and collect their results?
どのようにテストを実行し、結果を集めていますか?

Once you have tests, you'll want to run them. JUnit provides tools to define the suite to be run and to display its results. To run tests and see the results on the console, run:

一度テストを作成すれば、テストを実行したくなるでしょう。JUnitは実行するための一式を定義し、かつ結果を表示するツールを提供しています。コンソール上でテストを実行し結果を見るためには、次を事項します:
org.junit.runner.TextListener.run(TestClass1.class, ...); 
You make your JUnit 4 test classes accessible to a TestRunner designed to work with earlier versions of JUnit, declare a static method suite that returns a test.
JUnitの以前のバージョンで動作するよう設計されたテストランナーにアクセスするJUnit 4のテストクラスを作成するには、テストを戻り値とするstaticメソッドsuiteを宣言します。
public static junit.framework.Test suite() { 
    return new JUnit4TestAdapter(Example.class); 
}

Expected Exceptions

期待された例外

How do you verify that code throws exceptions as expected?
コードが予想通りの例外を送出することをどのように検証しますか?

Verifying that code completes normally is only part of programming. Making sure the code behaves as expected in exceptional situations is part of the craft of programming too. For example:

コードが正常に完了したことを検証することは、プログラミングの一面です。コードが異常ケースで予想通りの振舞いをしたことを確かめることも、プログラミング技術の一部です。例:
new ArrayList<Object>().get(0); 
This code should throw an IndexOutOfBoundsException. The @Test annotation has an optional parameter "expected" that takes as values subclasses of Throwable. If we wanted to verify that ArrayList throws the correct exception, we would write:
このコードはIndexOutOfBoundsExceptionを送出すべきです。@Testアノテーションは、Throwableのサブクラスの値を取る"expected"という任意のパラメータを持っています。ArrayListが正しい例外を送出することを検証したい場合は、次のように書いて下さい:
@Test(expected= IndexOutOfBoundsException.class) public void empty() { 
    new ArrayList<Object>().get(0); 
}