LoginSignup
14

More than 5 years have passed since last update.

JUnit : private methodsの引数nullの時の例外テストのやり方

Last updated at Posted at 2015-07-24

JUnitでprivate methodsのnullテストをする際に詰まったので、紹介します。
ついでに、それまでの過程を順を追って説明します。
説明は、コメント文で行います。

JUnitでのprivate methodのテスト

これは有名ですね。

privateTest.java
public class PrivateTest {
    @Test
    public void test() {
        // Methodを取得します
        // getMethodではなく, getDeclaredMethod
        Method method = Sample.class.getDeclaredMethod("privateMethod", String.class);
        // private methodにアクセスできるようにする。
        method.setAccessible(true);
        Sample sample = new Sample();
        // メソッドを呼び出し、テストする。
        assertEquals(Integer.valueOf(1), (Integer)method.invoke(sample, "A"));
    }
}

JUnitでのprivate methodの例外テスト

調べたら出てきます。

privateTest.java
public class PrivateTest {
    @Test(expected = IllegalArgumentException.class)
    public void test() {
        Method method = Sample.class.getDeclaredMethod("privateMethod", String.class);
        method.setAccessible(true);
        Sample sample = new Sample();
        // メソッドを呼び出し、例外を検知する。
        try {
            method.invoke(sample, ""));
            // invokeで例外が出たらInvocationTargetExceptionをなげる。
        } catch (final InvocationTargetException e) {
            // 投げられた本来の例外を取得する。
            final Throwable throwable = e.getCause();
            // 他の例外ではないかをチェックする。
            if (throwable instanceof IllegalArgumentException) {
                // キャストをして、なげる。
                throw (IllegalArgumentException) throwable;
            } else {
                Assert.fail();
            }
        }
        Assert.fail();
    }
}

JUnitでのprivate methodへの引数nullテスト

本題です。

privateTest.java
public class PrivateTest {
    @Test(expected = NullPointerException.class)
    public void test() {
        Method method = Sample.class.getDeclaredMethod("privateMethod", String.class);
        method.setAccessible(true);
        Sample sample = new Sample();
        try {
            // invoke(Object, Object...)
            // メソッドへ渡す引数が、Object...なので
            // new Object[]{null}として渡す。
            method.invoke(sample, new Object[]{ null }));
        } catch (final InvocationTargetException e) {
            final Throwable throwable = e.getCause();
            if (throwable instanceof NullPointerException) {
                throw (NullPointerException) throwable;
            } else {
                Assert.fail();
            }
        }
        Assert.fail();
    }
}

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
14