File tree Expand file tree Collapse file tree
core-java-lang-2/src/test/java/com/baeldung/exceptions
core-java/src/test/java/com/baeldung/exceptions Expand file tree Collapse file tree Original file line number Diff line number Diff 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 }
Original file line number Diff line number Diff line change 22
33import com .google .common .base .Throwables ;
44import org .apache .commons .lang3 .exception .ExceptionUtils ;
5+ import org .junit .jupiter .api .Assertions ;
56import org .junit .jupiter .api .Test ;
67
8+ import java .time .LocalDate ;
79import java .time .format .DateTimeParseException ;
10+ import java .time .temporal .ChronoUnit ;
811
912import static com .baeldung .exceptions .RootCauseFinder .*;
1013import static org .junit .jupiter .api .Assertions .assertTrue ;
1417 */
1518public 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 {
You can’t perform that action at this time.
0 commit comments