diff --git a/core-java/src/main/java/com/baeldung/exceptions/RootCauseFinder.java b/core-java/src/main/java/com/baeldung/exceptions/RootCauseFinder.java index 11f29a2cf0..e05dc7a6cd 100644 --- a/core-java/src/main/java/com/baeldung/exceptions/RootCauseFinder.java +++ b/core-java/src/main/java/com/baeldung/exceptions/RootCauseFinder.java @@ -33,28 +33,28 @@ public class RootCauseFinder { } try { - return calculateDifference(birthDate).getYears(); + return Period + .between(parseDate(birthDate), LocalDate.now()) + .getYears(); } catch (DateParseException ex) { throw new CalculationException(ex); } } - private static Period calculateDifference(String birthDateAsString) throws DateParseException { + private static LocalDate parseDate(String birthDateAsString) throws DateParseException { - LocalDate birthDate = null; + LocalDate birthDate; try { birthDate = LocalDate.parse(birthDateAsString); } catch (DateTimeParseException ex) { throw new InvalidFormatException(birthDateAsString, ex); } - LocalDate today = LocalDate.now(); - - if (birthDate.isAfter(today)) { + if (birthDate.isAfter(LocalDate.now())) { throw new DateOutOfRangeException(birthDateAsString); } - return Period.between(birthDate, today); + return birthDate; } } diff --git a/core-java/src/test/java/com/baeldung/exceptions/RootCauseFinderTest.java b/core-java/src/test/java/com/baeldung/exceptions/RootCauseFinderTest.java index c333a7ac26..cfac81b812 100644 --- a/core-java/src/test/java/com/baeldung/exceptions/RootCauseFinderTest.java +++ b/core-java/src/test/java/com/baeldung/exceptions/RootCauseFinderTest.java @@ -2,9 +2,12 @@ package com.baeldung.exceptions; import com.google.common.base.Throwables; import org.apache.commons.lang3.exception.ExceptionUtils; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import java.time.LocalDate; import java.time.format.DateTimeParseException; +import java.time.temporal.ChronoUnit; import static com.baeldung.exceptions.RootCauseFinder.*; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -14,6 +17,19 @@ import static org.junit.jupiter.api.Assertions.assertTrue; */ public class RootCauseFinderTest { + @Test + public void givenBirthDate_whenCalculatingAge_thenAgeReturned() { + try { + int age = AgeCalculator.calculateAge("1990-01-01"); + Assertions.assertEquals(1990, LocalDate + .now() + .minus(age, ChronoUnit.YEARS) + .getYear()); + } catch (CalculationException e) { + Assertions.fail(e.getMessage()); + } + } + @Test public void givenWrongFormatDate_whenFindingRootCauseUsingJava_thenRootCauseFound() { try {