3
votes

Is there a way to generate random dates for property tests using Scalacheck . I want to generate both future and past dates . But the existing Scalacheck.Gen class does not provide any predefined method to do so .

3

3 Answers

6
votes

The following will generate what you are looking for

implicit val localDateArb = Arbitrary(localDateGen)

def localDateGen: Gen[LocalDate] = {
    val rangeStart = LocalDate.MIN.toEpochDay
    val currentYear = LocalDate.now(UTC).getYear
    val rangeEnd = LocalDate.of(currentYear, 1, 1).toEpochDay
    Gen.choose(rangeStart, rangeEnd).map(i => LocalDate.ofEpochDay(i))
}
2
votes

For joda time, I have used like that:

lazy val localDateGen: Gen[LocalDate] = Gen.calendar map LocalDate.fromCalendarFields
0
votes

Actually, "to generate both future and past dates", the implementation below is more accurate:

def localDateGen: Gen[LocalDate] =
      Gen.choose(
        min = LocalDate.MIN.toEpochDay,
        max = LocalDate.MAX.toEpochDay
      ).map(LocalDate.ofEpochDay)
implicit val localDateArb = Arbitrary(localDateGen)