LoginSignup
0
0

More than 5 years have passed since last update.

junitで"The constructor Empty() is not visible"が発生する際の設定方法

Last updated at Posted at 2019-02-02

この記事の概要

eclipseでjunitを使用した際に、少し苦労したので、備忘録を兼ねて設定方法を記載します。
具体的にはテスト対象クラスにprivateコンストラクタがある際に下記エラーが発生することがあるので、その回避方法を記載します。

  The constructor Empty() is not visible

参考

Junitでprivateメソッドのテスト方法

JavaのリフレクションAPIでメソッド取得、メソッド実行

環境

OS:Windows8.1 32bit
eclipse:4.5.2

テスト対象クラス

TestTarget.java

packege com.web.test

public class TestTarget {

  private TestTarget() {
    //記述無し
  }

  private int minus(int x, int y) {
        return (x - y);
  }

}

junitテストクラス

テスト対象クラスに対するjunitのテストクラスを作成

SampleTest.java

import static org.junit.Assert.*;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.junit.Test;

public class SampleTest {

    @Test
    public void test()
        throws NoSuchMethodException,
        SecurityException,
        IllegalAccessException,
        IllegalArgumentException,
        InvocationTargetException
    {
        TestTarget testTarget = new TestTarget();

        Method method = Sample.class.getDeclaredMethod("minus", int.class, int.class);
        method.setAccessible(true);

        int actual = (int)method.invoke(testTarget, 8, 2);

        assertEquals(6, actual);
    }

このようにすると
 The constructor Empty() is not visible
が発生したので、下記のように変更します

SampleTest.java

import static org.junit.Assert.*;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.junit.Test;

public class SampleTest {

    @Test
    public void test()
        throws NoSuchMethodException,
        SecurityException,
        IllegalAccessException,
        IllegalArgumentException,
        InvocationTargetException
    {
        //修正前
        //TestTarget testTarget = new TestTarget();
                //修正後
                //リフレクションAPIを使用してテスト対象クラスのインスタンスを取得
        TestTarget testTarget = Class.forName("com.web.test.TestTarget").newInstance();

        Method method = testTarget.class.getDeclaredMethod("minus", int.class, int.class);
        method.setAccessible(true);

        int actual = (int)method.invoke(testTarget, 8, 2);

        assertEquals(6, actual);
    }

これで
 The constructor Empty() is not visible
が解消されました

0
0
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
0
0