我正在使用ScalaTest和ScalaCheck。我写了一个自定义生成器和任意生成器如下:
import java.time.LocalDateTime
import org.scalacheck._
import org.scalatest.PropSpec
import org.scalatest.prop.Checkers
import Gen._
import Arbitrary.arbitrary
class AuthJwtSpec extends PropSpec with Checkers {
private val start = LocalDateTime.now.atZone(java.time.ZoneId.systemDefault()).toEpochSecond
private val end = LocalDateTime.now.plusDays(2).atZone(java.time.ZoneId.systemDefault()).toEpochSecond
private val pickTime = Gen.choose(start, end)
private val authUser: Arbitrary[AuthUser] =
Arbitrary {
for {
u <- arbitrary[String]
p <- arbitrary[String]
} yield AuthUser(u, p)
}
property("Generate JWT token.") {
check(Prop.forAll(authUser, pickTime) {(r1: AuthUser, r2: Long) =>
???
})
}
}
问题是,r1
类型为Arbitrary[AuthUser]
,但我需要AuthUser
,如何获取?
答案 0 :(得分:1)
正如我所见,问题出在authUser
字段 - 它应该是Gen[AuthUser]
,而不是Arbitary[AuthUser]
:
import java.time.LocalDateTime
import org.scalacheck._
import org.scalatest._
import prop._
case class AuthUser(u: String, p: String)
class AuthJwtSpec extends PropSpec with Checkers with PropertyChecks {
private val start = LocalDateTime.now.atZone(java.time.ZoneId.systemDefault()).toEpochSecond
private val end = LocalDateTime.now.plusDays(2).atZone(java.time.ZoneId.systemDefault()).toEpochSecond
private val pickTime: Gen[Long] = Gen.choose(start, end)
// AuthUser should be Gen[AuthUser], not Arbitary[AuthUser]
private val authUser: Gen[AuthUser] =
for {
u <- Arbitrary.arbitrary[String]
p <- Arbitrary.arbitrary[String]
} yield AuthUser(u, p)
property("Generate JWT token.") {
val prop = Prop.forAll(authUser, pickTime) {(user: AuthUser, time: Long) =>
println(s"User: $user")
println(s"Time: $time")
// Property checks must always return true or false
true
}
check(prop)
}
}