I am a beginner in the Scala / ZIO 2 world, and I am trying to write some tests for a simple service.
so I have this method:
def validate(id: String): ZIO[Any, Throwable, Unit] = {
if (id == "invalid-id") {
ZIO.fail("Invalid id")
}
}
I tried several things, but mainly I tried to use the isFailure
or the fails
assertions:
suite("My suite")(
test("When id is valid") { // This passes
for {
result <- validate("valid-id")
} yield assertTrue(result == ())
},
test("when id is not valid") {
for {
result <- validate("invalid-id")
} yield assertTrue(isFailure(result)) // This doesn't even compile
}
)
How can I test the failure case of an effect?
I am using:
Scala: "3.2.1"
zio: "2.0.4"
zio-test: "2.0.5"
There are multiple ways to assert that an effect has failed. The below example demonstrates the use of
ZIO#exit
andZIO#flip
.