如何使用私有构造函数测试最终类?

时间:2014-08-18 18:13:15

标签: java unit-testing

如何测试这样的类(参见下面的代码)?

public final class A {

    public static final String FIRST = "1st";
    public static final String SECOND = "2nd";

    private A() {
        // NOP
    }
}

现在我的所有覆盖工具都说构造函数不包含测试。我的测试看起来像这样:

assertEquals(A.FIRST, "1st");
assertEquals(A.SECOND, "2nd");

我如何测试我的班级?

UPD

此代码解决了我的问题。

@Test
public void magic() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
    Constructor<A> constructor = A.class.getDeclaredConstructor();
    constructor.setAccessible(true);
    A instance = constructor.newInstance();

    assertNotNull(instance);
}

是的,我同意这不是最好的解决方案。但它有效:)

1 个答案:

答案 0 :(得分:4)

反思可能是要走的路:How do I test a class that has private methods, fields or inner classes?

顺便说一下,这可能是所提供链接中问题的重复。

或者,您是否可以创建一个protected的包装器方法,它只是转发所有对private方法的调用?