lift value out of / or into ZIO to assert it

103 Views Asked by At

I have a ZIO that looks like this:

ZIO[transactor.Transactor[Task], Serializable, String]

and I need to assert the String, that is in that ZIO with another plain String.

So my question is:

How can I assert the plain String, with the String in the ZIO, or

can I lift the String into that same ZIO, to assert it with this one:

ZIO[transactor.Transactor[Task], Serializable, String]

I´m working with ZIO-Test as my testing framework.

2

There are 2 best solutions below

0
l33tHax0r On

I got this based on the rock the jvm zio course. Important things are highlighted in the comments

package com.w33b

import zio.test._
import zio._


object ZIOAssert extends ZIOSpecDefault {

  class ATask

  abstract class Transact[ATask] {
    def get(): String
    
    def put(ATask: ATask): ATask
  }

// This is the mock service that we will use to create a ZLayer
  val mockTransact = ZIO.succeed(new Transact[ATask] {
    override def get(): String = "hello"
    override def put(aTask: ATask): ATask = new ATask
  })

// This is the method we are testing and we need a service (Zlayer) associated with it. 
// We then use the service to invoke a method to get our return value

  def methodUnderTest: ZIO[Transact[ATask], Serializable, String] = {
    for {
      trans <- ZIO.service[Transact[ATask]]
      tVal = trans.get()
    } yield tVal
  } 
  def spec = suite("Let's test that ZIO lift")(
    test("lets test that lift") {
      assertZIO(methodUnderTest)(Assertion.equalTo("hello"))
    }
  ).provide(ZLayer.fromZIO(mockTransact)) // Important to provide the layer or we can't test

}

0
Nabil A. On

with ZIO 2.x

val spec = suite("tetst")(
  test("whatever"){
    val effect: ZIO[transactor.Transactor[Task], Serializable, String] = ???
    val expected: String = ???
    for {
      value <- effect
    } yield assertTrue(value == expected)
  }
)

In general, you just create here a ZIO with the assertion in the success channel.