0

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?

Community
  • 1
  • 1
Richard
  • 5,840
  • 36
  • 123
  • 208

1 Answers1

2

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);
}
Ben Green
  • 3,953
  • 3
  • 29
  • 49
  • 1
    Good answer, but be aware that time zone is crucial in determining today’s date. This code relies implicitly on the JVM’s current default time zone. That default can change at any moment, even during runtime. I recommend being explicit, passing the expected/desired time zone to the call to `now` method. – Basil Bourque Jan 08 '16 at 17:12
  • @BasilBourque Thanks for the comment. You are of course correct. I always pass a time zone in my production code, but I assumed that as these were unit tests it would all be done on the same JVM. However, better to be safe than sorry :) – Ben Green Jan 11 '16 at 09:03