Skip to content

Commit e257fc3

Browse files
marcos-lgmikr
authored andcommitted
AgeCalculator changes
1 parent 89dddae commit e257fc3

2 files changed

Lines changed: 23 additions & 7 deletions

File tree

core-java-modules/core-java-lang-2/src/test/java/com/baeldung/exceptions/RootCauseFinder.java

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -33,28 +33,28 @@ public static int calculateAge(String birthDate) throws CalculationException {
3333
}
3434

3535
try {
36-
return calculateDifference(birthDate).getYears();
36+
return Period
37+
.between(parseDate(birthDate), LocalDate.now())
38+
.getYears();
3739
} catch (DateParseException ex) {
3840
throw new CalculationException(ex);
3941
}
4042
}
4143

42-
private static Period calculateDifference(String birthDateAsString) throws DateParseException {
44+
private static LocalDate parseDate(String birthDateAsString) throws DateParseException {
4345

44-
LocalDate birthDate = null;
46+
LocalDate birthDate;
4547
try {
4648
birthDate = LocalDate.parse(birthDateAsString);
4749
} catch (DateTimeParseException ex) {
4850
throw new InvalidFormatException(birthDateAsString, ex);
4951
}
5052

51-
LocalDate today = LocalDate.now();
52-
53-
if (birthDate.isAfter(today)) {
53+
if (birthDate.isAfter(LocalDate.now())) {
5454
throw new DateOutOfRangeException(birthDateAsString);
5555
}
5656

57-
return Period.between(birthDate, today);
57+
return birthDate;
5858
}
5959

6060
}

core-java-modules/core-java/src/test/java/com/baeldung/exceptions/RootCauseFinderTest.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,12 @@
22

33
import com.google.common.base.Throwables;
44
import org.apache.commons.lang3.exception.ExceptionUtils;
5+
import org.junit.jupiter.api.Assertions;
56
import org.junit.jupiter.api.Test;
67

8+
import java.time.LocalDate;
79
import java.time.format.DateTimeParseException;
10+
import java.time.temporal.ChronoUnit;
811

912
import static com.baeldung.exceptions.RootCauseFinder.*;
1013
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -14,6 +17,19 @@
1417
*/
1518
public class RootCauseFinderTest {
1619

20+
@Test
21+
public void givenBirthDate_whenCalculatingAge_thenAgeReturned() {
22+
try {
23+
int age = AgeCalculator.calculateAge("1990-01-01");
24+
Assertions.assertEquals(1990, LocalDate
25+
.now()
26+
.minus(age, ChronoUnit.YEARS)
27+
.getYear());
28+
} catch (CalculationException e) {
29+
Assertions.fail(e.getMessage());
30+
}
31+
}
32+
1733
@Test
1834
public void givenWrongFormatDate_whenFindingRootCauseUsingJava_thenRootCauseFound() {
1935
try {

0 commit comments

Comments
 (0)