我是猫和函数式编程的新手,并且正在尝试测试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)
答案 0 :(得分:3)
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))
}
}
}