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

Flo*_*erl 5 java unit-testing scala scala-cats

情景

在我目前正在编写的应用程序中,我在IOApp中使用了cat -effect 的IO monad

如果从命令行参数“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 Code Online (Sandbox Code Playgroud)

现在,我想测试例如我的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?
  }
}
Run Code Online (Sandbox Code Playgroud)

我的问题

我能否以某种方式“搜索/迭代 IO monad”并确定我的程序是否包含来自调试循环的语句?我必须打电话program.unsafeRunSync()给它检查吗?

Yuv*_*kov 2

您可以在自己的方法内部实现逻辑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] = ???
}
Run Code Online (Sandbox Code Playgroud)

然后在你的测试中:

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
    }
  }
}
Run Code Online (Sandbox Code Playgroud)