Last active
August 4, 2016 15:22
-
-
Save 4lberto/4faf01dac7ddf609daed7bc707843cd5 to your computer and use it in GitHub Desktop.
Test Private Constructor
This file contains 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
//La clase a testear | |
private OrderRepositorySQLQueries(){ | |
throw new UnsupportedOperationException(); | |
} | |
/** | |
* Utility class to test private constructor of utility classes. Those classes must return UnsupportedOperationException (and be final...) | |
* | |
* @param <T> | |
*/ | |
public class AbstractPrivateConstructorTest<T>{ | |
@SuppressWarnings("unchecked") | |
@Test | |
public void shouldTestPrivateConstructor(){ | |
//given | |
Constructor<T> c; | |
try{ | |
final Class<T> persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()) | |
.getActualTypeArguments()[0]; | |
c = (Constructor<T>) persistentClass.getDeclaredConstructors()[0]; | |
c.setAccessible(true); | |
assertThat("Class must be final", Modifier.isFinal(persistentClass.getModifiers()), is(true)); | |
//when | |
final T u = c.newInstance(); | |
Assert.fail(); | |
}catch(SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | |
| InvocationTargetException e){ | |
//then | |
assertThat("The cause of the inner exception must be UnsupportedOperationException when trying to instance", | |
e.getCause().getClass().getName(), is(UnsupportedOperationException.class.getName())); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment