0

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

M Reza
  • 18,350
  • 14
  • 66
  • 71
  • Seems like a duplicate of https://stackoverflow.com/questions/156503/how-do-you-assert-that-a-certain-exception-is-thrown-in-junit-4-tests?rq=1 (Junit 4) or https://stackoverflow.com/questions/40268446/junit-5-how-to-assert-an-exception-is-thrown (JUnit 5). – dtanabe Jan 19 '19 at 04:40

1 Answers1

0

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);
}
Jonathan JOhx
  • 5,784
  • 2
  • 17
  • 33