Merge pull request #9959 from j0rdanit0/BAEL-4534

Added code examples for BAEL-4534
This commit is contained in:
Eric Martin 2020-09-13 10:56:13 -05:00 committed by GitHub
commit 840c588179
1 changed files with 34 additions and 0 deletions

View File

@ -0,0 +1,34 @@
package com.baeldung.checkclassexistence;
import org.junit.Test;
public class CheckClassExistenceUnitTest {
public static class InitializingClass {
static {
if (true) { //enable throwing of an exception in a static initialization block
throw new RuntimeException();
}
}
}
@Test(expected = ClassNotFoundException.class) //thrown when class does not exist
public void givenNonExistingClass_whenUsingForName_thenClassNotFound() throws ClassNotFoundException {
Class.forName("class.that.does.not.exist");
}
@Test
public void givenExistingClass_whenUsingForName_thenNoException() throws ClassNotFoundException {
Class.forName("java.lang.String");
}
@Test(expected = ExceptionInInitializerError.class) //thrown when exception occurs inside of a static initialization block
public void givenInitializingClass_whenUsingForName_thenInitializationError() throws ClassNotFoundException {
Class.forName("com.baeldung.checkclassexistence.CheckClassExistenceUnitTest$InitializingClass");
}
@Test
public void givenInitializingClass_whenUsingForNameWithoutInitialization_thenNoException() throws ClassNotFoundException {
Class.forName("com.baeldung.checkclassexistence.CheckClassExistenceUnitTest$InitializingClass", false, getClass().getClassLoader());
}
}