LoginSignup
9
12

More than 5 years have passed since last update.

JUnitの徒然

Posted at

設計、製造と終わってJUnitに着手している。

JUnitもほぼ未経験なので、言葉の理解とトライアンドエラーとなった部分をメモ。

  • DBUnit
    Excelに書いたデータをDBに入れてくれる便利な部品。
    今のPJでは、テストclassの親になるAbstractClassを作っていて、initializeDatabase、finalizeDatabaseと書くだけで
    実行できるような工夫がされててさらに便利。

  • DataPoints、Theory
    テストケースを書くのに便利なアノテーション。
    @DataPointsで、パターン化したテストケースの型(fixture)を用意し、
    @Theoryで、メソッド引数に入れる事で自動的にパターン数分の呼び出しがされる。
    fixtureには、「テストメソッドの引数+期待値」を全部定義しておくと、IN・OUTが1箇所に集められるので見やすい。

サンプル
@RunWith(Theories.class)
public class ServiceImplTest extends AbstractClass {
public static class MethodFixture {// 内部クラス
        public final Long input1;
        public final Long input2;
        public final String return;

        MethodFixture(Long input1, Long input2, String return) {
            this.input1 = input1;
            this.input2 = input2;
            this.return = return;
        }
    }

@DataPoints
    public static MethodFixture [] METHOD_FIXTURE = {
            new MethodFixture (10L, 100L, true), // OKパターン
            new MethodFixture (10L, 500L, false), // NGパターン1
            new MethodFixture (40L, 100L, false), // NGパターン2
            new MethodFixture (40L, null, false),// 例外パターン
    };// テストケースが一覧化できる

@Theory
    public void testMethod_検証(MethodFixture fixture) {
        String actual = service.method(fixture.input1, fixture.input2,fixture.return);

        assertThat(actual, is(fixture.return));
    }
}

内部クラスを使ったテストケース設計は、パラメータにクラスを持ったメソッドだと手間だな~と感じた。
内部クラスのコンストラクタには配列化して渡して、内部でうまくくっ付ける、とか、小細工してどうにか切り抜けてる。

9
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
12