0

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, "name@email.com", 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, "name@email.com", 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.

Michael Zajac
  • 55,144
  • 7
  • 113
  • 138
Shurik Agulyansky
  • 2,607
  • 2
  • 34
  • 76
  • 1
    The parameter is not optional — it is required to supply a value for it. The type of that value happens to be `Option`, though, which means that the value you supply must be a `Some` or `None`. – Seth Tisue Dec 12 '15 at 03:32

2 Answers2

4

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, "name@email.com", true, verCode, Some(verCodeSentDate))

Some vs Option. Also, “case class” doesn't need “new” to create a new object

Community
  • 1
  • 1
pons
  • 61
  • 3
1

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)
freakybit
  • 59
  • 5