通用断言失败

时间:2016-05-17 16:09:53

标签: java unit-testing generics reflection code-coverage

我在Java中有一个简单的通用静态方法,它对于具有私有构造函数的类失败。这是方法:

public static <E> void assertThatCtorIsPrivate(Class<E> clazz, Class<?>... parameters) throws NoSuchMethodException, InstantiationException, IllegalAccessException {
    Preconditions.checkNotNull(clazz);
    final Constructor<?> constructor = clazz.getConstructor(parameters);
    constructor.setAccessible(true);
    try {
        constructor.newInstance((Object[]) null);
    } catch(InvocationTargetException e) {
        if(e.getCause() instanceof UnsupportedOperationException) {
            throw new UnsupportedOperationException();
        }
    } finally {
        constructor.setAccessible(false);
    }

    assert Modifier.isPrivate(constructor.getModifiers());
}

以下是我要测试的课程:

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import com.google.common.base.Preconditions;
import com.google.gson.Gson;

public final class DecodeJson {

    private static final Gson GSON = new Gson();

    private DecodeJson() {
        throw new UnsupportedOperationException();
    }

    public static <E> E parse(final File file, Class<E> clazz) throws IOException {
        Preconditions.checkNotNull(file);
        Preconditions.checkArgument(file.exists() && file.canRead());
        return GSON.fromJson(new FileReader(file), clazz);
    }

    public static <E> E parse(final String content, Class<E> clazz) throws IOException {
        Preconditions.checkNotNull(content);
        Preconditions.checkArgument(content.length() != 0);
        return GSON.fromJson(content, clazz);
    }

}

在我的单元测试中,我只是:

@Test(expected = UnsupportedOperationException.class)
public void testPrivateCtor() throws NoSuchMethodException, InstantiationException, IllegalAccessException {
    ReflectionHelper.assertThatCtorIsPrivate(DecodeJson.class);
}

我拨打NoSuchMethodException时收到final Constructor<?> constructor = clazz.getConstructor(parameters);。我已经尝试用?代替E但仍然没有骰子。有什么见解吗?

1 个答案:

答案 0 :(得分:2)

执行Class.getConstructor(Class<?>... parameterTypes)只会返回可访问的构造函数。

肯定无法从外部访问private构造函数。

要获取不可访问的构造函数,请使用Class.getDeclaredConstructor(Class<?>... parameterTypes)

相关问题