@RunWith(Enclosed.class)
久しぶりにテストクラスを書いたらしょぼいところでつまずいてしまったのでメモ。
@RunWith(Enclosed.class) とは
テストクラスを構造化したい場合に利用する。
例えばこんなクラスがあって、
public class Sample { public Sample() { } public String hoge() { return "hoge"; } public boolean huga(int num) { if(num >= 0) { return true; } return false; } }
メソッドごとにテストクラスを書きたい、みたいな場合には@RunWith(Enclosed.class)をつけてメソッドごとのインナークラスを作成すれば良い。
import static org.junit.Assert.*; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; @RunWith(Enclosed.class) public class SampleTest { /** * hogeメソッドのテスト */ public static class hogeTest { @Test public void test1() { Sample target = new Sample(); String result = target.hoge(); assertEquals("hoge", result); } } /** * hugaメソッドのテスト */ public static class hugaTest { @Test public void test1() { Sample target = new Sample(); boolean result = target.huga(0); assertTrue(result); } @Test public void test2() { Sample target = new Sample(); boolean result = target.huga(-1); assertFalse(result); } } }
実行時には全部実行するか特定のテストクラスだけ実行するかを選べる。
つまずきポイント
インナークラスがないのにのに@RunWith(Enclosed.class) をつけてしまうとテストが動かない。
import static org.junit.Assert.*; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; @RunWith(Enclosed.class) //構造化していない(インナークラスがない)のに記述 public class SampleTest { @Test public void hoge_test1() { Sample target = new Sample(); String result = target.hoge(); assertEquals("hoge", result); } @Test public void huga_test1() { Sample target = new Sample(); boolean result = target.huga(0); assertTrue(result); } @Test public void huga_test2() { Sample target = new Sample(); boolean result = target.huga(-1); assertFalse(result); } }
エラーだったりExceptionが発生したりはせず、でも実行数は0という事態になる。