Skip to content

Instantly share code, notes, and snippets.

@PeterPerhac
Last active February 20, 2021 20:44
Show Gist options
  • Save PeterPerhac/9a388f1d10945a2d6a29414ad79a8268 to your computer and use it in GitHub Desktop.
Save PeterPerhac/9a388f1d10945a2d6a29414ad79a8268 to your computer and use it in GitHub Desktop.
Making assertions about Scala Futures and cats OptionT[Future, T] and EitherT[Future, L, R]
import cats.data.{EitherT, OptionT}
import org.scalatest.{Assertion, TestSuite}
import scala.concurrent.Future
trait FutureAssertions {
self: TestSuite =>
import org.scalatest.MustMatchers._
import org.scalatest.concurrent.ScalaFutures._
implicit class FutureReturns(f: Future[_]) {
def returns(o: Any): Assertion = whenReady(f)(_ mustBe o)
def failedWith(e: Exception): Assertion = whenReady(f.failed)(_ mustBe e)
def failedWith[T <: Throwable](exClass: Class[T]): Assertion = whenReady(f.failed)(_.getClass mustBe exClass)
}
implicit class OptionTReturns[T](ot: OptionT[Future, T]) {
def returnsSome(t: T): Assertion = whenReady(ot.value)(_ mustBe Some(t))
def returnsNone: Assertion = whenReady(ot.value)(_ mustBe Option.empty[T])
def failedWith(e: Exception): Assertion = whenReady(ot.value.failed)(_ mustBe e)
}
implicit class EitherTReturns[L, R](et: EitherT[Future, L, R]) {
def returnsRight(value: R): Assertion = whenReady(et.value)(_ mustBe Right(value))
def returnsLeft(value: L): Assertion = whenReady(et.value)(_ mustBe Left(value))
def failedWith(e: Exception): Assertion = whenReady(et.value.failed)(_ mustBe e)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment