Santiago Molano
Santiago Molano

Reputation: 21

How can I test my private constructors that throws an exception

I would like to know how can I test my private constructors that throws an IllegalStateException, I have search and found something like this:

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

and this is the constructor:

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

the test works if the constructors doesnt throw an exception

Upvotes: 0

Views: 1608

Answers (1)

Jonathan JOhx
Jonathan JOhx

Reputation: 5968

Add the optional expected attribute to the @Test annotation. By following way test that passes when the expected IllegalStateException is raised:

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

Or you can catch the exception and validate it by following way:

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

Upvotes: 0

Related Questions