Skip to content

Instantly share code, notes, and snippets.

@ridencww
Created August 15, 2015 03:44
Show Gist options
  • Save ridencww/c1d82c76966c68f3b011 to your computer and use it in GitHub Desktop.
Save ridencww/c1d82c76966c68f3b011 to your computer and use it in GitHub Desktop.
JUnit test that verifies that a class cannot be instantiated
Given class...
public class MyClass {
private MyClass() throws InstantiationException {
throw new InstantiationException("Instances of this type are forbidden.");
}
...
}
This is the test to ensure class cannot be instantiated...
@Test
public void test_no_instantiations() throws Exception {
Constructor constructor = MyClass.class.getDeclaredConstructors()[0];
constructor.setAccessible(true);
try {
constructor.newInstance((Object[])null);
fail("Expected construction failure");
} catch (InvocationTargetException ex) {
Throwable targetException = ex.getTargetException();
assertNotNull(targetException);
assertEquals(targetException.getClass(), InstantiationException.class);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment