【问题标题】:Generic assertion failing通用断言失败
【发布时间】:2016-05-17 16:09:52
【问题描述】:

我在 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);
}

当我拨打final Constructor&lt;?&gt; constructor = clazz.getConstructor(parameters); 时,我收到了NoSuchMethodException。我试过用? 代替E,但仍然没有骰子。有什么见解吗?

【问题讨论】:

  • 你想在这里证明什么?你能不能把类本身变成静态的?
  • @MarkChorley Java 中的顶级类不能是静态的。这是为了看到 100% 的代码覆盖率,所以我有那种温暖、模糊的感觉。

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


【解决方案1】:

执行Class.getConstructor(Class&lt;?&gt;... parameterTypes) 只会返回可访问的构造函数。

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

要获取不可访问的构造函数,请使用Class.getDeclaredConstructor(Class&lt;?&gt;... parameterTypes)

【讨论】:

  • 啊...我想这是注重细节的关键时刻之一。谢谢!
猜你喜欢
  • 1970-01-01
  • 2011-05-27
  • 2021-03-16
  • 2010-09-26
  • 2018-11-09
  • 2021-01-20
  • 2014-06-10
  • 2014-02-10
相关资源
最近更新 更多