|
| 1 | +package com.baeldung.noexception; |
| 2 | + |
| 3 | +import com.machinezoo.noexception.Exceptions; |
| 4 | +import org.junit.Test; |
| 5 | +import org.slf4j.Logger; |
| 6 | +import org.slf4j.LoggerFactory; |
| 7 | + |
| 8 | +public class NoExceptionUnitTest { |
| 9 | + |
| 10 | + private static Logger logger = LoggerFactory.getLogger(NoExceptionUnitTest.class); |
| 11 | + |
| 12 | + @Test |
| 13 | + public void whenStdExceptionHandling_thenCatchAndLog() { |
| 14 | + try { |
| 15 | + System.out.println("Result is " + Integer.parseInt("foobar")); |
| 16 | + } catch (Throwable exception) { |
| 17 | + logger.error("Caught exception:", exception); |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + @Test |
| 22 | + public void whenDefaultNoException_thenCatchAndLog() { |
| 23 | + |
| 24 | + Exceptions.log().run(() -> System.out.println("Result is " + Integer.parseInt("foobar"))); |
| 25 | + } |
| 26 | + |
| 27 | + @Test |
| 28 | + public void givenLogger_whenDefaultNoException_thenCatchAndLogWithClassName() { |
| 29 | + System.out.println("Result is " + Exceptions.log(logger).get(() -> +Integer.parseInt("foobar")).orElse(-1)); |
| 30 | + } |
| 31 | + |
| 32 | + @Test |
| 33 | + public void givenLoggerAndMessage_whenDefaultNoException_thenCatchAndLogWithClassNameAndMessage() { |
| 34 | + System.out.println("Result is " + Exceptions.log(logger, "Something went wrong:").get(() -> +Integer.parseInt("foobar")).orElse(-1)); |
| 35 | + } |
| 36 | + |
| 37 | + @Test |
| 38 | + public void givenDefaultValue_whenDefaultNoException_thenCatchAndLogPrintDefault() { |
| 39 | + System.out.println("Result is " + Exceptions.log(logger, "Something went wrong:").get(() -> +Integer.parseInt("foobar")).orElse(-1)); |
| 40 | + } |
| 41 | + |
| 42 | + @Test(expected = Error.class) |
| 43 | + public void givenCustomHandler_whenError_thenRethrowError() { |
| 44 | + CustomExceptionHandler customExceptionHandler = new CustomExceptionHandler(); |
| 45 | + customExceptionHandler.run(() -> throwError()); |
| 46 | + } |
| 47 | + |
| 48 | + @Test |
| 49 | + public void givenCustomHandler_whenException_thenCatchAndLog() { |
| 50 | + CustomExceptionHandler customExceptionHandler = new CustomExceptionHandler(); |
| 51 | + customExceptionHandler.run(() -> throwException()); |
| 52 | + } |
| 53 | + |
| 54 | + private static void throwError() { |
| 55 | + throw new Error("This is very bad."); |
| 56 | + } |
| 57 | + |
| 58 | + private static void throwException() { |
| 59 | + String testString = "foo"; |
| 60 | + testString.charAt(5); |
| 61 | + } |
| 62 | + |
| 63 | +} |
0 commit comments