JUnit privateメソッドの例外処理をテスト

実現したいこと

privateメソッドの中でExceptionを投げています。
事情により、(呼出元であるpublicメソッドではなく)privateメソッドのテストの必要があり
例外の内容を確認したいですが、try {} catch {}でうまくcatchできません。

該当のソースコード

テスト対象クラス

Java

1public class TargetClass {2 public void publicMethod(Integer i) {3 privateMethod(i);4 }5 6 private void privateMethod(Integer i) {7 if (i == 0) {8 throw new MyCustomExcetion(this.getClass(), "error message01");9 } else {10 throw new MyCustomExcetion(this.getClass(), "error message02");11 }12 }13}

テストクラス

Java

1@RunWith(PowerMockRunner.class)2public class TargetClassTest {3 @InjectMocks4 TargetClass target;5 6 @Test7 public void privateTest() throws Exception {8 Method method = TargetClass.class.getDeclaredMethod(9 "privateMethod", Integer.class);10 method.setAccessible(true);11 12 TargetClass spy = PowerMockito.spy(target);13 14 try {15 method.invoke(spy, 1)16 } catch (MyCustomException e) {17 assertThat(e.getErrorMessage(), is("error message02"); // catchできる想定だが、デバックしてもここに来ない18 }19 }20}

試したこと

①発生しているExceptionを確認

Java

1 @Test2 public void privateTest() throws Exception {3 Method method = TargetClass.class.getDeclaredMethod(4 "privateMethod", Integer.class);5 method.setAccessible(true);6 7 TargetClass spy = PowerMockito.spy(target);8 9 try {10 method.invoke(spy, 1)11 } catch (MyCustomException e) {12 assertThat(e.getErrorMessage(), is("error message02"); // catchできる想定だが、デバックしてもここに来ない13 } catch (Exception e)14 assertThat(e.getClass(), is(MyCustomException.class); // java.lang.AssertionErrorが発生している15 }16 }

②expectedを確認
→成功するが、ErrorMessageを確認したいため不十分。

Java

1 @Test(expected = MyCustomException.class)2 public void privateTest() throws Exception {3 Method method = TargetClass.class.getDeclaredMethod(4 "privateMethod", Integer.class);5 method.setAccessible(true);6 7 TargetClass spy = PowerMockito.spy(target);8 9 try {10 method.invoke(spy, 1)11 } catch (MyCustomException e) {12 assertThat(e.getErrorMessage(), is("error message02"); // catchできる想定だが、デバックしてもここに来ない13 }14 }

コメントを投稿

0 コメント