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 .
Asked
Active
Viewed 3,035 times
3 Answers
7
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))
}

Stephen Thompson
- 29
- 1
- 6

Aravind Yarram
- 78,777
- 46
- 231
- 327
-
1@truptirath looks like you should accept the answer, if it met your needs. – tilde May 20 '21 at 21:17
3
For joda time, I have used like that:
lazy val localDateGen: Gen[LocalDate] = Gen.calendar map LocalDate.fromCalendarFields

Stephen Thompson
- 29
- 1
- 6

Дмитрий Завориин
- 27
- 1
2
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)

Terry BRUNIER
- 137
- 6