AgeCalculator changes
This commit is contained in:
parent
c59d9dbf8f
commit
cdd14b23f7
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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 {
|
||||
|
|
Loading…
Reference in New Issue