trupti rath
trupti rath

Reputation: 71

How to generate time using scalacheck generators?

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 .

Upvotes: 4

Views: 3427

Answers (3)

Terry BRUNIER
Terry BRUNIER

Reputation: 157

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)

Upvotes: 2

For joda time, I have used like that:

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

Upvotes: 3

Aravind Yarram
Aravind Yarram

Reputation: 80194

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))
}

Upvotes: 7

Related Questions