Thiago Pereira
Thiago Pereira

Reputation: 1712

Catch exception in Play 2 Test + Futures

how do I catch an exception inside a future success using play to test?

Here is my code:

"A Validity" should {
    "be created based on Client's Mobile" in new WithApplication {
      val objectId = UUIDs.timeBased()
      CValidityServiceModule.checkValidity(true, "MOBILE", clientId, objectId)
      val future = genericService.findByObjectIdAndByClientId(objectId, clientId)

      future.onComplete {
        case Success(s) => {
          s match {
            case Some(v) => {
              v.clientId mustEqual clientId
              v.objectId mustEqual objectId
            }
            case None => assert(false)
          }
        }
        case Failure(t) => {
          assert(false, t.getMessage)
        }
      }
    }

Basically if any matcher fail, it trows me an exception, but the test is green.

Any idea?

Upvotes: 0

Views: 154

Answers (1)

Michael Zajac
Michael Zajac

Reputation: 55569

You need to wait for the Future to complete before testing it. Using the onComplete callback won't work because the test completes before the Future, and the exception is thrown in a different context.

Await.result should do it for you:

import scala.concurrent.Await
import scala.concurrent.duration.Duration
val future = genericService.findByObjectIdAndByClientId(objectId, clientId)
val s = Await.result(future, Duration.Inf)
s match {
  case Some(v) => {
    v.clientId mustEqual clientId
    v.objectId mustEqual objectId
  }
  case None => assert(false)
}

Upvotes: 2

Related Questions