假设我测试一个函数echo: String => String
,它只是重复输入,使用specs2
.
我可以写一些这样的测试:
class EchoSpec extends SpecificationWithJUnit {
"echo should handle ASCII alphanumeric names" in {
echo("abc") must beEqualTo("abc")
}
"echo should handle names with slashes" in {
echo("a/b/c") must beEqualTo("a/b/c")
}
"echo should handle names with dots" in {
echo("a.b.c") must beEqualTo("a.b.c")
}
"echo should handle non-ASCII names" in {
echo("אבג") must beEqualTo("אבג")
}
}
但是,我更愿意摆脱样板代码。所以我正在使用cats
幺半群:
import cats.implicits._
def testEcho(expected: String): String => Option[String] = {str =>
if (str == expected) none else s"$str != expected".some
}
def testEchoes(expected: List[String]): Option[String] =
expected foldMap testEcho map (_.mkString(", "))
"echo should handle all names" {
val expected = List("abc", "a/b/c", "a.b.c", "אבג")
testEcho(expected) must beNone
}
是否有意义 ?如何改进/简化它?幺半群在这里真的有必要吗?我可以在没有monoid的情况下摆脱上面的样板代码吗?