0

假设我测试一个函数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的情况下摆脱上面的样板代码吗?

4

2 回答 2

1
List("abc", "a/b/c", "a.b.c", "אבג")
  .foreach(s => echo(s) must beEqualTo(s))
于 2017-03-08T15:09:29.013 回答
1

您还可以使用 ScalaCheck

class EchoSpec extends SpecificationWithJUnit with ScalaCheck {
  "echo should handle all names" >> prop { s: String =>
    echo(s) must beEqualTo(s)
  }
}
于 2017-03-09T07:01:54.653 回答