Skip to content

Instantly share code, notes, and snippets.

@mihkels
Last active January 4, 2017 15:06
Show Gist options
  • Save mihkels/0a56d37a1a411c05d112e81226d65bdc to your computer and use it in GitHub Desktop.
Save mihkels/0a56d37a1a411c05d112e81226d65bdc to your computer and use it in GitHub Desktop.
Sometimes (i.e util classes) there is need to verify in tests that constructor is private. Best way in my opinion is to do it using Java reflection and below is almost drop in solution how it should be done. Only thing that needs to be replaced is the class under test
public class PrivateConstructorTest {
@Test
public void utilClassConstructorMustBePrivate() throws Exception {
// Replace ReportBuilderUtils with class name under test
final Constructor<ReportBuilderUtils> constructor = ReportBuilderUtils.class.getDeclaredConstructor();
assertThat(Modifier.isPrivate(constructor.getModifiers())).isTrue();
constructor.setAccessible(true);
constructor.newInstance();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment