How to check for an exception thrown in a future

642 views
Skip to first unread message

Christian Kaps

unread,
Apr 26, 2014, 9:35:49 AM4/26/14
to specs2...@googlegroups.com
Hi,

I would like to check if an exception was thrown in a future. I had the idea to wrap the exception with a FutureException in the recover method of a future, and then test first against the outer exception (FutureException) and then against the wrapped exception (SilhouetteException). But it doesn't work for me with Specs2. How could I achieve this with Specs2.

Thanks,
Christian

Paulo "JCranky" Siqueira

unread,
Apr 26, 2014, 12:45:11 PM4/26/14
to specs2...@googlegroups.com
Why not simply evaluate the future and see if it results in a failure?

[]s,


--
You received this message because you are subscribed to the Google Groups "specs2-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to specs2-users...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
[]s,

Paulo "JCranky" Siqueira
youtube | site | lojinha

Christian Kaps

unread,
Apr 27, 2014, 9:48:17 AM4/27/14
to specs2...@googlegroups.com
Hi,

Thanks for your answer. Consider the following method:

def process(request: Request): Future[Result] = {
request.param match {
case Some(param) => methodWhichReturnsFuture(param)
case None => throw new Exception()
}
}

No if I test the method I would use:

Await.result(process(request), 60.seconds) must throwA[Exception]

But now I can't distinguish which exception was thrown.

Is there an other method to check if the exception in the future was
thrown?

Thanks,
Christian

Am Samstag, den 26.04.2014, 13:45 -0300 schrieb Paulo "JCranky"
Siqueira:

etorreborre

unread,
Apr 27, 2014, 7:29:00 PM4/27/14
to specs2...@googlegroups.com
Can you use the failed method?

deffailedFuture[Throwable]


If you block on this, you will get the thrown exception. You can test it like that:

    import scala.concurrent._
    import duration._

    val f = Future {throw new IllegalArgumentException("hey"); 1}.failed

    lazy val result = Await.result(f, 1.second)
    
    result must not(throwAn[Exception])
    result.rethrow must throwAn[IllegalArgumentException]("hey")
  

    implicit class Rethrow(t: Throwable) {
      def rethrow = {throw t; t}
    }

Eric.

Christian Kaps

unread,
Apr 28, 2014, 2:35:49 PM4/28/14
to specs2...@googlegroups.com
Works like a charm.

Thanks,
Christian

Am Sonntag, den 27.04.2014, 16:29 -0700 schrieb etorreborre:
> Can you use the failed method?
>
>
> def
> failed: Future[Throwable]
> --
> You received this message because you are subscribed to a topic in the
> Google Groups "specs2-users" group.
> To unsubscribe from this topic, visit
> https://groups.google.com/d/topic/specs2-users/MhJxnvyS1_Q/unsubscribe.
> To unsubscribe from this group and all its topics, send an email to
Reply all
Reply to author
Forward
0 new messages