gpt4 book ai didi

scala - 猫 EitherT 和效果的匹配器

转载 作者:行者123 更新时间:2023-12-02 00:10:42 28 4
gpt4 key购买 nike

我是 cat 和函数式编程方面的新手,我正在努力对 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)

最佳答案

specs2-cats提供 IOMatchers启用以下语法的特征

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))
}
}
}

关于scala - 猫 EitherT 和效果的匹配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59234283/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com