0
假设我测试功能echo: String => String
,它只是重复输入,与specs2
。Simple单元测试简单单元测试
我可以写一个这样的几个测试:
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
monoids:
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
}
它有道理吗?如何改进/简化它? 幺半群在这里真的有必要吗?如果没有幺半群,我可以摆脱上面的样板代码吗?
谢谢!很高兴知道'ScalaCheck'可以与'specs2'集成。我想用恒定的字符串列表来测试'echo' – Michael
还有可能:'prop((s:String)=> echo(s)必须是equals(s))。setGen(Gen.oneOf(strings:_ *))' – Eric
再次感谢。如上所示,它真的比'strings foreach {s => echo(s)must equal to(s)}'更好吗? – Michael