diff --git a/src/test/java/com/h2/Module06_Test.java b/src/test/java/com/h2/Module06_Test.java index 0b510b81a..0d2686a90 100644 --- a/src/test/java/com/h2/Module06_Test.java +++ b/src/test/java/com/h2/Module06_Test.java @@ -3,6 +3,7 @@ import org.junit.jupiter.api.Test; import org.junit.platform.commons.function.Try; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Optional; @@ -12,6 +13,7 @@ public class Module06_Test { private final String classToFind = "com.h2.Utilities"; + public Optional> getUtilitiesClass() { Try> aClass = tryToLoadClass(classToFind); return aClass.toOptional(); @@ -43,4 +45,32 @@ public void m6_02_testGetLongValueExistence() { fail("Can't find a method with name " + methodName + " in class " + classToFind + " with 1 parameter of type 'String'"); } } + + @Test + public void m6_03_testGetLongValueCorrectness() throws IllegalAccessException, InvocationTargetException { + final String methodName = "getLongValue"; + final Optional> maybeClass = getUtilitiesClass(); + assertTrue(maybeClass.isPresent(), classToFind + " should be present"); + assertEquals(classToFind, maybeClass.get().getCanonicalName()); + + final Class aClass = maybeClass.get(); + try { + Method method = aClass.getMethod(methodName, String.class); + { + long result = (long) method.invoke(null, "123"); + assertEquals(123L, result, methodName + " should convert '123' into '123L'"); + } + { + String input = "1.22"; + final InvocationTargetException exception = assertThrows(InvocationTargetException.class, () -> method.invoke(null, input)); + Throwable targetException = exception.getTargetException(); + assertEquals(IllegalArgumentException.class, targetException.getClass(), methodName + " should have thrown an instance of 'IllegalArgumentException'"); + assertEquals(input + " cannot be converted into a 'long' value. Exiting program.", targetException.getMessage()); + } + + } catch (NoSuchMethodException e) { + fail("Can't find a method with name " + methodName + " in class " + classToFind + " with 1 parameter of type 'String'"); + } + + } }