Reputation: 2603
I have a model class as follows:
case class UserEmail(id: Muid,
audit: AuditMetadata,
email: String,
emailVerified: Boolean,
emailVerificationCodeId: Muid,
emailVerificationSentDate: Option[DateTime]) {
...
}
And I am trying to play with a unit tests for it:
class UserEmailSpec extends Specification with Mockito {
"UserEmail Model test" should {
"return correct values when properly constructed" in {
val muid = mock[Muid]
val auditMetadata = mock[AuditMetadata]
val verCode = mock[Muid]
val verCodeSentDate = DateTime.now()
val userEmail = new UserEmail(muid, auditMetadata, "[email protected]", true, verCode, verCodeSentDate)
userEmail.emailVerified must beTrue
userEmail.emailVerificationSentDate must beAnInstanceOf[DateTime]
}
}
}
At this point, I am getting a following error:
#.../UserEmailSpec.scala:24: type mismatch;
[error] found : org.joda.time.DateTime
[error] required: Option[org.joda.time.DateTime]
[error] val userEmail = new UserEmail(muid, auditMetadata, "[email protected]", true, verCode, verCodeSentDate)
[error] ^
[error] one error found
[error] (test:compile) Compilation failed
[error] Total time: 6 s, completed Dec 12, 2015 1:04:46 AM
I also tried mocking the DateTime object and got the same result. The only condition in which this thing works, is if I am passing null as emailVerificationSentDate.
What am I missing.
Upvotes: 0
Views: 89
Reputation: 59
Instance of Option[A] can have two forms - either a Some(A) or None. A valid assignment of verCodeSentDate would be:
val verCodeSentDate = Some(DateTime.now())
The type of verCodeSentDate would be then Option[DateTime]. The purpose of Option type is to avoid NullPointerExceptions, it is NOT an optional argument! If you would like to declare an optional argument, you can provide a default value:
def fun(optionalArgumentInt: Int = 10, optionalArgumentOption: Option[Int]) = Some(10)
Upvotes: 1
Reputation: 61
In UserEmail case class, verCodeSentDate is declared as an Option type. In Scala Option class is used when value might be present (Some
) or not (None
).
Try.
UserEmail(muid, auditMetadata, "[email protected]", true, verCode, Some(verCodeSentDate))
Some vs Option. Also, “case class” doesn't need “new” to create a new object
Upvotes: 4