【问题标题】:How can I test my private constructors that throws an exception如何测试引发异常的私有构造函数
【发布时间】:2019-01-19 04:31:17
【问题描述】:

我想知道如何测试引发 IllegalStateException 的私有构造函数,我已经搜索并发现了类似这样的内容:

@Test
public void privateConstructorTest()throws Exception{
    Constructor<DetailRecord> constructor = DetailRecord.class.getDeclaredConstructor();
    assertTrue(Modifier.isPrivate(constructor.getModifiers()));
    constructor.setAccessible(true);
    constructor.newInstance();
}

这是构造函数:

private DetailRecord(){
    throw new IllegalStateException(ExceptionCodes.FACTORY_CLASS.getMessage());
}

如果构造函数没有抛出异常,则测试有效

【问题讨论】:

标签: java testing junit constructor private


【解决方案1】:

将可选的期望属性添加到 @Test 注释。通过以下方式测试在引发预期的 IllegalStateException 时通过:

@Test(expected=IllegalStateException.class)
public void privateConstructorTest() {
    Constructor<DetailRecord> constructor = DetailRecord.class.getDeclaredConstructor();
    assertTrue(Modifier.isPrivate(constructor.getModifiers()));
    constructor.setAccessible(true);
    constructor.newInstance();
}

或者您可以捕获异常并通过以下方式对其进行验证:

@Test
public void privateConstructorTest() {
    Constructor<DetailRecord> constructor = DetailRecord.class.getDeclaredConstructor();
    assertTrue(Modifier.isPrivate(constructor.getModifiers()));
    constructor.setAccessible(true);
    Throwable currentException = null;
    try {
        constructor.newInstance();
    catch (IllegalStateException exception) {
        currentException = exception;
    }
    assertTrue(currentException instanceof IllegalStateException);
}

【讨论】:

  • 不行,我执行测试的时候出现这个,ava.lang.reflect.InvocationTargetException,Caused by: java.lang.IllegalStateException
  • InvocationTargetException的原因私有构造函数抛出的异常
  • 好的,然后将异常和错误消息更改为 InvocationTargetException 以便比较它
猜你喜欢
  • 1970-01-01
  • 2018-06-16
  • 1970-01-01
  • 2019-03-12
  • 2014-05-27
  • 1970-01-01
  • 1970-01-01
  • 2019-03-09
  • 2018-01-16
相关资源
最近更新 更多