Search code examples
scalascalatestzio

Scala, ZIO - how to test if effect returned success?


I have a simple test code which check mocked service:

 runtime.unsafeRun(service.run.forkDaemon)
    eventually(Timeout(Span(5, Seconds)), Interval(Span(1, Seconds))) {
      verify(someMockResult).create(any[String], any[String])
    }

The service returns Task[Done]. It works ok, but I would like to check also if this unsafeRun returns succeed. I tried to do it like this:

runtime.unsafeRun(service.run.forkDaemon) shouldBe succeed

or:

val result = runtime.unsafeRun(service.run.forkDaemon)
   eventually(Timeout(Span(5, Seconds)), Interval(Span(1, Seconds))) {
      result shouldBe succeed
   }

But it does not work. Is there any way to check if effect result is succeed?


Solution

  • First of all, you misunderstood the meaning of org.scalatest.Succeed (which is aliased by succeed). It is needed only when you need to end up the body of a function with the Assertion type. It is equal to assert(true) basically. It is not an assertion that actually tests something.

    If I understood right that you want to check the execution of your testTask that we define as:

    val testTask: Task[Done] = service.run.forkDaemon
    

    The problem in your code that val res = runtime.unsafeRun(testTask) executes it synchronously. This means that this line of code evaluates with two possible outcomes: 1) it successfully executes testTask and assigns the result to the res variable, or 2) execution of testTask fails, and it throws an exception.

    So, basically, if there is no exception, it is succeeded.

    Another way to check this more conveniently is to evaluate it to Future with runtime.unsafeRunToFuture and then assert that future is eventually succeeded. You can do it with, for example, like this:

    assert(
      future.value match { 
        case Some(Success(_)) => true 
        case _ => false
      }
    )