【问题标题】:Matchers for cats EitherT and effects猫的匹配器 EitherT 和效果
【发布时间】:2020-04-01 16:40:51
【问题描述】:

我是猫和函数式编程的新手,我在单元测试函数数据类型(如EitherT)方面遇到了困难。有示例代码:

class Library[F[_]]() {
    def create(book: Book)(implicit M: Monad[F]): EitherT[F, BookAlreadyExistsError, Book] = ...
}

我想使用 Spec2 对其进行测试,但我不知道如何正确进行。尝试过这样的事情,但它不起作用:

  val library = Library[IO]()

  test("create book") {

    val book = Book("Title 1", 2016, "author 1")
    (for (
      resultBook <- library.create(book)
    ) yield resultBook shouldEqual ???
    ).unsafeRunSync()

  }

我想要这样的非常简单的断言:

   resultBook shouldEqual Right(Book("Title 1", 2016, "author 1"))
   // or
   resultBook shouldEqual Left(BookAlreadyExistsError)

【问题讨论】:

    标签: scala functional-programming scala-cats specs2 cats-effect


    【解决方案1】:

    specs2-cats 提供了IOMatchers trait,它支持以下语法

    library.create(book).value must returnValue(Right(book))
    

    在哪里

    libraryDependencies += "org.specs2" %% "specs2-core" % "4.8.1" % Test,
    libraryDependencies += "org.specs2" %% "specs2-cats" % "4.8.1" % Test,
    

    这是一个工作示例

    import cats.data.EitherT
    import cats.effect.IO
    import org.specs2.mutable.Specification
    import org.specs2.matcher.IOMatchers
    
    class CatsSpec extends Specification with IOMatchers {
      case class Book(title: String, year: Int, author: String)
      def create(book: Book): EitherT[IO, String, Book] = EitherT(IO(Right(book).withLeft[String]))
      val book = Book("Title 1", 2016, "author 1")
    
      "specs2-cats dependency" should {
        "provide matcher for IO effect" in {
          create(book).value must returnValue(Right(book))
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-29
      • 1970-01-01
      • 1970-01-01
      • 2017-11-21
      • 1970-01-01
      • 2020-12-23
      • 2022-06-14
      • 2018-08-09
      • 2019-04-09
      相关资源
      最近更新 更多