0
votes

For my Java application I am trying to use ScalaCheck to write some property-based unit tests. For that purpose I need generators, but all the tutorials I can find use a constructor with parameters to generate objects. The object I need to generate does not have constructor parameters, and I cannot add such a constructor since it is from an external library.

I now have the following (JwtClaims is from the package org.jose4j.jwt):

def genClaims: Gen[JwtClaims] = {
    val url = arbString
    val username = arbString

    val claims = new JwtClaims()
    claims.setNotBeforeMinutesInThePast(0)
    claims.setExpirationTimeMinutesInTheFuture(60)
    claims.setSubject(username) // error about Gen[String] not matching type String

    claims
}

Any suggestions on how to write my generator? I have zero knowledge of Scala, so please be patient if I've made an 'obvious' mistake :) My expertise is in Java, and testing using ScalaCheck is my first venture into Scala.

1

1 Answers

3
votes

You need to be returning a generator of a claims object, not a claims object. The generator is effectively a function that can return a claims object. The normal way I go about this is with a for comprehension (other people prefer flatMap, but I think this reads more clearly).

  def genClaims: Gen[JwtClaims] = {
    for {
      url <- arbitrary[String]
      username <- arbitrary[String]
    } yield {
      val claims = new JwtClaims()
      claims.setNotBeforeMinutesInThePast(0)
      claims.setExpirationTimeMinutesInTheFuture(60)
      claims.setSubject(username)
      claims
    }
  }