scalaziozio-test

How does one assert a single field in error type?


Let's assume I have code such as this:

final case class CustomException(errorCode: Int, id: UUID) extends Throwable

val logic: ZIO[Any, Throwable, Unit] = ???

I would like to use ZIO Test to check for a specific error case

val checkForTimeout = testM("Logic should time out") {
  for {
    result <- logic.flip
  } yield assert(result, isSubtype[CustomException](???))
}

What I would like to do is check the errorCode field for a specific value. But it seems the existing combinators in ZIO Test only allow me to check the the full object. I would like to only check for _.errorCode while ignoring _.id, which means equalTo is not a good enough combinator for this use case.

How would I go about addressing this?


Solution

  • You can use Assertion.hasField, which lets you "zoom in" on one part of a larger structure, to do this.

    val checkForTimeout = testM("Logic should time out") {
      for {
        result <- logic.flip
      } yield assert(
          result,
          isSubtype[CustomException](hasField("errorCode", _.errorCode, equalTo(1)))
        )
    }