java - 通用断言失败

标签 java unit-testing generics reflection code-coverage

我在 Java 中有一个简单的通用静态方法,对于具有私有(private)构造函数的类来说失败了。方法如下:

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());
}

这是我要测试的类(class):

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但仍然没有骰子。有什么见解吗?

最佳答案

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

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

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

关于java - 通用断言失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37281372/

相关文章:

java - 我可以直接从 RecyclerView 获取实体房间数据并将其保存到房间数据库吗?

android - 如何在命令行上使用gradlew运行特定的测试?

unit-testing - Dart 测试大致相等

java - 我无法从 JDialog 更新 Jcombobox(通过模型)

java - 在Java中,条件表达式是线程安全操作吗?

c# - 创建一个采用泛型类型的 IEnumerable 类型的方法

java - 类型安全的对象组合

java - 扩展一个类,其中父类的参数扩展了一个类

java - 为什么在 Graphics 对象上调用 dispose() 会导致 JPanel 不呈现任何组件

unit-testing - 如何使用 HUnit 和 Cabal 进行自动化测试?