简体   繁体   English

Scala ZIO 测试断言 IO

[英]Scala ZIO test assert an IO

I have a function with return type RIO as follows:我有一个返回类型为 RIO 的函数,如下所示:

object Compresser {
  val buffer = ZManaged.fromAutoCloseable(ZIO.succeed(new ByteArrayOutputStream()))

  val stream = for {
    b <- buffer
    s <- ZManaged.fromAutoCloseable(ZIO.succeed(new DeflaterOutputStream(b, false)))
  } yield (b, s)

  def compress(input: Array[Byte]): RIO[blocking.Blocking, Array[Byte]] = stream.use { case (buffer, stream) =>
    for {
      () <- blocking.effectBlocking(stream.write(input))
      () <- blocking.effectBlocking(stream.flush())
      result = buffer.toByteArray
    } yield result
  }
}

I am having trouble writing a unit test for this function, is there any way to check if the returned result is a Throwable or Array[Byte] and compare the actual result with the expected?我在为此函数编写单元测试时遇到问题,有什么方法可以检查返回的结果是 Throwable 还是 Array[Byte] 并将实际结果与预期结果进行比较? Something like this:像这样的东西:

object CompresserSpec extends DefaultRunnableSpec{

  def spec = suite("Compresser")(
    test("Compress an empty string") {
      val input = ""
      val expected = Array[Byte](0, 0, 0, -1, -1, 3, 0)
      val output: IO[Throwable, Array[Byte]] = compress(input.getBytes("UTF-8")).provide(Has(Blocking))
      //Something like: assert(output)(equalTo(expected))
    },
    test("Compress null") {
      val output: IO[Throwable, Array[Byte]] = compress(null).provide(Has(Blocking))
      //Something like: assert(output)(NullPointerException)
    } 
  )
}

Turns out what I need is just a testM comes with a for comprehension原来我需要的只是一个带有理解的 testM

object ZDeflaterSpec extends DefaultRunnableSpec{

  def spec : ZSpec[Environment, Failure] = suite("Compresser")(
    testM("Compress an empty string") {
      val input = ""
      val expected = Array[Byte](0, 0, 0, -1, -1, 3, 0)
      for {
        output <- compress(input.getBytes("UTF-8")).provide(Has(Blocking.Service.live))
      } yield assert(output)(equalTo(expected))
    },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM