Home > Mobile >  NullPointerException: because this method call was *not* stubbed correctly
NullPointerException: because this method call was *not* stubbed correctly

Time:06-09

I am trying to run this test case in scala using mockito but i see the following error. can anyone suggest to me what am I doing wrong?

This is the Test case that I am running

Test case

class MailerServiceSpec extends BaseSpec {
  val http: HttpExt = mock[HttpExt]
  val mailService: NotificationService = mock[NotificationService]
  val rawJobResponse: JsObject = Json.obj(("aman","verma"))

  "Send Emails to multiple/single user" should {
    "send email to user" in {
      when(http.singleRequest(any[HttpRequest], any[HttpsConnectionContext], any[ConnectionPoolSettings], any[LoggingAdapter])) thenReturn
        future(HttpResponse(status = StatusCodes.OK, entity = httpEntity(rawJobResponse)))
      whenReady(mailService.sendMessage(any[String],any[String],any[String])(any[ExecutionContext])){ result =>
        assert(result == Done)
      }
    }
  }
}

This is the sendMessage method of mailerService that I want to test.

NotificationService.scala

override def sendMessage(receivers: List[String], subject: String, content: String)(implicit
    ec: ExecutionContext
  ): Future[Done] = {

    val notification = Notification(
      recipients = receivers,
      cc = Nil,
      bcc = Nil,
      sender = sender,
      htmlBody = content,
      htmlTitle = subject
    )

    val httpHeader = RawHeader("SENDGRID_API_KEY", sendgridApiKey)
    (for {
      entity <- Marshal(notification).to[MessageEntity]
      _ <- makeHttpRequest(
        HttpRequest(POST, notificationEmailUrl, entity = entity).addHeader(httpHeader)
      )
    } yield Done).andThen {
      case Failure(exception) => logger.error("Failed to send email", exception)
    }

  }

Error

You have a NullPointerException here:
-> at org.scalatest.concurrent.ScalaFutures$$anon$1.futureValueImpl(ScalaFutures.scala:294)
because this method call was *not* stubbed correctly:
-> at scala.Option.orElse(Option.scala:477)
notificationService.sendMessage(
    null,
    null,
    null,
    null
);

CodePudding user response:

You are calling notificationService in your test but it's a mock and you didn't define its behaviour.

I think you don't want to mock it but build a real NotificationService, otherwise you're just testing nothing.

  • Related