Junit(Junit4使用)を持ちいたテスト対象クラスにprivateメソッドがある場合のテストコードの書き方についてご質問させていただきたいです。
以下テスト対象クラス
public final class Util{ private Util(){ } public static boolean check(String arg){ boolean result = false; if (arg == null){ result = true; } return result; } }
以下テストクラス
public class UtilTest{ @SuppressWarnings("static-accsess") @Test public void test() throws Exception{ //期待値 Boolean expected = true; //Util test = new Util(); ←インスタンスの生成はできない //テスト対象メソッド読み込み Method method = Util.class.getDeclareMethod("check", Boolean.class); //privateメソッドにアクセス可能にする method.setAccessible(true); //actual = trueになる想定 Boolean actual = (Boolean)method.invokke(Util.class, "null"); //比較検証 assertEquals(expected, actual); } }
privateメソッドの呼び出しを行う場合は上記のように記載するとあり、同様に書きましたが、
デバッグ実行したところ、Method method = Util.class.getDeclareMethod("check", Boolean.class);
でエラーがでて、NoSuchMethodExceptionが発生しているという状況で原因がわからず困っております。
Utilクラスでコンストラクタの修飾子をprivateにしており、インスタンスが生成できずcheckメソッドのテストもできません。
こちらの対処法について回答をいただけると幸いです。

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/05/16 12:33
2022/05/16 12:47
2022/05/16 22:45