Created
August 15, 2015 03:44
-
-
Save ridencww/c1d82c76966c68f3b011 to your computer and use it in GitHub Desktop.
JUnit test that verifies that a class cannot be instantiated
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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