繁体   English   中英

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

[英]How can I test my private constructors that throws an exception

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM