Reputation: 21
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
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