使用cat-effect的IO monad进行单元测试

问题描述 投票:2回答:2

The Scenario

在我正在写的一个应用程序中,我在IO monad中使用cat-effect的IOApp

如果以命令行参数'debug'开头,我将程序流删除到等待用户输入并执行各种调试相关方法的调试循环中。一旦开发人员在没有任何输入的情况下按下enter,应用程序将退出调试循环并退出main方法,从而关闭应用程序。

这个应用程序的主要方法看起来大致如下:

import scala.concurrent.{ExecutionContext, ExecutionContextExecutor}
import cats.effect.{ExitCode, IO, IOApp}
import cats.implicits._

object Main extends IOApp {

    val BlockingFileIO: ExecutionContextExecutor = ExecutionContext.fromExecutor(blockingIOCachedThreadPool)

    def run(args: List[String]): IO[ExitCode] = for {
        _ <- IO { println ("Running with args: " + args.mkString(","))}
        debug = args.contains("debug")
        // do all kinds of other stuff like initializing a webserver, file IO etc.
        // ...
        _ <- if(debug) debugLoop else IO.unit
    } yield ExitCode.Success

    def debugLoop: IO[Unit] = for {
      _     <- IO(println("Debug mode: exit application be pressing ENTER."))
      _     <- IO.shift(BlockingFileIO) // readLine might block for a long time so we shift to another thread
      input <- IO(StdIn.readLine())     // let it run until user presses return
      _     <- IO.shift(ExecutionContext.global) // shift back to main thread
      _     <- if(input == "b") {
                  // do some debug relevant stuff
                  IO(Unit) >> debugLoop
               } else {
                  shutDown()
               }
    } yield Unit

    // shuts down everything
    def shutDown(): IO[Unit] = ??? 
}

现在,我想测试是否例如我的run方法在我的ScalaTests中表现得像预期的那样:

import org.scalatest.FlatSpec

class MainSpec extends FlatSpec{

  "Main" should "enter the debug loop if args contain 'debug'" in {
    val program: IO[ExitCode] = Main.run("debug" :: Nil)
    // is there some way I can 'search through the IO monad' and determine if my program contains the statements from the debug loop?
  }
}

My Question

我可以以某种方式'搜索/遍历IO monad'并确定我的程序是否包含来自调试循环的语句?我是否必须打电话给program.unsafeRunSync()检查?

java scala unit-testing scala-cats
2个回答
1
投票

你可以在你自己的方法中实现run的逻辑,然后测试它,你不受限于返回类型,并将run转发给你自己的实现。由于run强迫你的手到IO[ExitCode],你可以用返回值来表达。通常,没有办法“搜索”IO值,因为它只是一个描述具有副作用的计算的值。如果你想检查它的潜在价值,你可以通过在世界末日运行它(你的main方法),或者你的测试,你unsafeRunSync它。

例如:

sealed trait RunResult extends Product with Serializable
case object Run extends RunResult
case object Debug extends RunResult

def run(args: List[String]): IO[ExitCode] = {
  run0(args) >> IO.pure(ExitCode.Success)
}

def run0(args: List[String]): IO[RunResult] = {
  for {
    _ <- IO { println("Running with args: " + args.mkString(",")) }
    debug = args.contains("debug")
    runResult <- if (debug) debugLoop else IO.pure(Run)
  } yield runResult
}

def debugLoop: IO[Debug.type] =
  for {
    _ <- IO(println("Debug mode: exit application be pressing ENTER."))
    _ <- IO.shift(BlockingFileIO) // readLine might block for a long time so we shift to another thread
    input <- IO(StdIn.readLine()) // let it run until user presses return
    _ <- IO.shift(ExecutionContext.global) // shift back to main thread
    _ <- if (input == "b") {
      // do some debug relevant stuff
      IO(Unit) >> debugLoop
    } else {
      shutDown()
    }
  } yield Debug

  // shuts down everything
  def shutDown(): IO[Unit] = ???
}

然后在你的测试中:

import org.scalatest.FlatSpec

class MainSpec extends FlatSpec {

  "Main" should "enter the debug loop if args contain 'debug'" in {
    val program: IO[RunResult] = Main.run0("debug" :: Nil)
    program.unsafeRunSync() match {
      case Debug => // do stuff
      case Run => // other stuff
    }
  }
}

1
投票

要搜索一些monad表达式,它必须是值,而不是语句,也就是具体化。这是着名的免费monad背后的核心理念。如果你在一些“代数”中表达你的代码的麻烦,因为他们称之为(想想DSL)它并通过Free将其提升为monad表达式嵌套,那么是的,你将能够搜索它。有很多资源可以解释免费monad比我在这里谷歌是你的朋友更好。

我的一般建议是,良好测试的一般原则适用于所有地方。隔离副作用部分并将其注入主逻辑部分,以便您可以在测试中注入假实现以允许各种断言。

© www.soinside.com 2019 - 2024. All rights reserved.