Files
jack/error-handling/ErrorHandlingMain.java

253 lines
10 KiB
Java

/**
* MIT License
*
* Copyright (c) 2021 Exercism
* Copyright (c) 2026 Networked Embedded Systems, University of Duisburg-Essen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import java.util.Optional;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
public class ErrorHandlingMain {
@Test(name = "Throws IllegalArgumentException")
public void testThrowIllegalArgumentException() {
runTest(() -> {
ErrorHandling errorHandling = new ErrorHandling();
assertThrows(Exception.class, () -> errorHandling.handleErrorByThrowingIllegalArgumentException(), false,
null);
});
}
@Test(name = "Throws IllegalArgumentException with provided detail message")
@Disabled
public void testThrowIllegalArgumentExceptionWithDetailMessage() {
runTest(() -> {
ErrorHandling errorHandling = new ErrorHandling();
assertThrows(IllegalArgumentException.class, () -> errorHandling
.handleErrorByThrowingIllegalArgumentExceptionWithDetailMessage("This is the detail message."),
false, "This is the detail message.");
});
}
@Test(name = "Throws any checked exception")
@Disabled
public void testThrowAnyCheckedException() {
runTest(() -> {
ErrorHandling errorHandling = new ErrorHandling();
assertThrows(Exception.class, () -> errorHandling.handleErrorByThrowingAnyCheckedException(), true, null);
});
}
@Test(name = "Throws any checked exception with provided detail message")
@Disabled
public void testThrowAnyCheckedExceptionWithDetailMessage() {
runTest(() -> {
ErrorHandling errorHandling = new ErrorHandling();
assertThrows(Exception.class,
() -> errorHandling
.handleErrorByThrowingAnyCheckedExceptionWithDetailMessage("This is the detail message."),
true, "This is the detail message.");
});
}
@Test(name = "Throws any unchecked exception")
@Disabled
public void testThrowAnyUncheckedException() {
runTest(() -> {
ErrorHandling errorHandling = new ErrorHandling();
assertThrows(RuntimeException.class, () -> errorHandling.handleErrorByThrowingAnyUncheckedException(),
false, null);
});
}
@Test(name = "Throws any unchecked exception with provided detail message")
@Disabled
public void testThrowAnyUncheckedExceptionWithDetailMessage() {
runTest(() -> {
ErrorHandling errorHandling = new ErrorHandling();
assertThrows(RuntimeException.class,
() -> errorHandling
.handleErrorByThrowingAnyUncheckedExceptionWithDetailMessage("This is the detail message."),
false, "This is the detail message.");
});
}
@Test(name = "Throws custom checked exception")
@Disabled
public void testThrowCustomCheckedException() {
runTest(() -> {
ErrorHandling errorHandling = new ErrorHandling();
assertThrows(CustomCheckedException.class,
() -> errorHandling.handleErrorByThrowingCustomCheckedException(), false, null);
});
}
@Test(name = "Throws custom checked exception with provided detail message")
@Disabled
public void testThrowCustomCheckedExceptionWithDetailMessage() {
runTest(() -> {
ErrorHandling errorHandling = new ErrorHandling();
assertThrows(CustomCheckedException.class, () -> errorHandling
.handleErrorByThrowingCustomCheckedExceptionWithDetailMessage("This is the detail message."), false,
"This is the detail message.");
});
}
@Test(name = "Throws custom unchecked exception")
@Disabled
public void testThrowCustomUncheckedException() {
runTest(() -> {
ErrorHandling errorHandling = new ErrorHandling();
assertThrows(CustomUncheckedException.class,
() -> errorHandling.handleErrorByThrowingCustomUncheckedException(), false, null);
});
}
@Test(name = "Throws custom unchecked exception with provided detail message")
@Disabled
public void testThrowCustomUncheckedExceptionWithDetailMessage() {
runTest(() -> {
ErrorHandling errorHandling = new ErrorHandling();
assertThrows(CustomUncheckedException.class, () -> errorHandling
.handleErrorByThrowingCustomUncheckedExceptionWithDetailMessage("This is the detail message."),
false, "This is the detail message.");
});
}
@Test(name = "Handles error by throwing Optional instance")
@Disabled
public void testReturnOptionalInstance() {
runTest(() -> {
ErrorHandling errorHandling = new ErrorHandling();
Optional<Integer> successfulResult = errorHandling.handleErrorByReturningOptionalInstance("1");
assertOptionalPresentWithValue(successfulResult, 1);
Optional<Integer> failureResult = errorHandling.handleErrorByReturningOptionalInstance("a");
assertOptionalNotPresent(failureResult);
});
}
private void runTest(Runnable body) {
try {
body.run();
System.out.println("TEST PASSED");
} catch (Exception | AssertionError t) {
System.out.println("TEST FAILED: " + t.getMessage());
}
}
private void assertThrows(Class<? extends Throwable> expectedType, Runnable body, boolean notRuntime,
String expectedMessage) {
try {
body.run();
throw new AssertionError(
"Expected exception of type " + expectedType.getName() + " but nothing was thrown");
} catch (Exception t) {
if (!expectedType.isAssignableFrom(t.getClass())) {
throw new AssertionError(
"Expected exception of type " + expectedType.getName() + " but was " + t.getClass().getName());
}
if (notRuntime && RuntimeException.class.isAssignableFrom(t.getClass())) {
throw new AssertionError(
"Expected a checked exception but got runtime exception " + t.getClass().getName());
}
if (expectedMessage != null && (t.getMessage() == null || !t.getMessage().equals(expectedMessage))) {
throw new AssertionError(
"Expected exception message '" + expectedMessage + "' but was '" + t.getMessage() + "'");
}
}
}
private void assertOptionalPresentWithValue(Optional<Integer> opt, int expected) {
if (!opt.isPresent())
throw new AssertionError("Expected Optional to be present");
if (!Integer.valueOf(expected).equals(opt.get()))
throw new AssertionError("Expected Optional value " + expected + " but was " + opt.get());
}
private void assertOptionalNotPresent(Optional<?> opt) {
if (opt.isPresent())
throw new AssertionError("Expected Optional to be empty");
}
public static void main(String[] args) {
new ErrorHandlingMain().runTests();
}
/**
* Annotation to mark test methods. The name parameter is used to identify the
* test in the output.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
private @interface Test {
String name();
}
/**
* Annotation to mark test methods as disabled. Disabled tests will not be
* executed when running the tests.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
private @interface Disabled {
}
private void runTests() {
Method[] methods = this.getClass().getDeclaredMethods();
List<Method> allTestMethods = Arrays.asList(methods).stream().filter(m -> m.isAnnotationPresent(Test.class))
.collect(Collectors.toList());
List<Method> enabledTestMethods = allTestMethods.stream().filter(m -> !m.isAnnotationPresent(Disabled.class))
.collect(Collectors.toList());
System.out
.println("Running " + enabledTestMethods.size() + " out of " + allTestMethods.size() + " tests... \n");
for (Method method : enabledTestMethods) {
try {
System.out.println("Running test: " + method.getAnnotation(Test.class).name());
method.invoke(this);
} catch (Exception e) {
System.out.println("Test " + method.getAnnotation(Test.class).name()
+ " failed with an unexpected exception: " + e.getCause());
}
}
System.out.println("Finished running tests.");
if (allTestMethods.size() != enabledTestMethods.size()) {
System.out.println("\nThe following tests are disabled and were not executed:");
for (Method method : allTestMethods) {
if (method.isAnnotationPresent(Disabled.class)) {
System.out.println("- " + method.getAnnotation(Test.class).name());
}
}
System.out.println(
"To enable these tests, remove the @Disabled annotation from the corresponding test methods.");
}
}
}