Reputation: 6116
I am trying to write test cases for a certain class. I want to set the test user's age to a certain value but I don't want to have to deal with the age calculation and/or making the junit test case time-independent, which I know how to do thanks to @SkinnyJ from my earlier post.
So is there a way to do something like:
LocalDate birthday = new LocalDate(72Y3M);
72 years and 3 months old being the desired age of the user. And then joda-time would take that number and calculate what his/her birthday should be to be that age and return that date. So in this case birthday would be October 8, 1943
.
Attempt 1:
public LocalDate setUsersAge(int years, int months, int days) {
LocalDate birthday = new LocalDate();
birthday.minusYears(years);
birthday.minusMonths(months);
birthday.minusDays(days);
return birthday
}
Attempt 2:
public LocalDate setUsersAge(int years, int months, int days) {
Period age = new Period();
age.withYears(years);
age.withMonths(months);
age.withDays(days);
return birthday.minus(age);
}
While both way get the job done, I just don't like how the code looks. Is there a much cleaner way to do this?
Upvotes: 0
Views: 378
Reputation: 4121
I think this is a fairly clean way of achieving your objective:
public LocalDate setUsersAge(int years, int months, int days) {
return LocalDate.now().minusYears(years).minusMonths(months).minusDays(days);
}
EDIT: Thanks to the comment from Basil Bourque, if you are worried about issues with timeZone, you can do the following:
public LocalDate setUsersAge(int years, int months, int days, DateTimeZone timeZone) {
return LocalDate.now(timeZone).minusYears(years).minusMonths(months).minusDays(days);
}
Upvotes: 2