如何测试抛出异常的私有构造函数

时间:2019-01-19 04:31:17

标签: java testing junit constructor private

我想知道如何测试抛出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());
}

如果构造函数没有引发异常,则测试有效

1 个答案:

答案 0 :(得分:0)

将可选的期望属性添加到 @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);
}
相关问题