2017-03-08 169 views
0

假設我測試功能echo: String => String,它只是重複輸入,與specs2Simple單元測試簡單單元測試

我可以寫一個這樣的幾個測試:

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 
} 

它有道理嗎?如何改進/簡化它? 幺半羣在這裏真的有必要嗎?如果沒有幺半羣,我可以擺脫上面的樣板代碼嗎?

回答

1
List("abc", "a/b/c", "a.b.c", "אבג") 
    .foreach(s => echo(s) must beEqualTo(s)) 
1

您還可以使用ScalaCheck

class EchoSpec extends SpecificationWithJUnit with ScalaCheck { 
    "echo should handle all names" >> prop { s: String => 
    echo(s) must beEqualTo(s) 
    } 
} 
+0

謝謝!很高興知道'ScalaCheck'可以與'specs2'集成。我想用恆定的字符串列表來測試'echo' – Michael

+1

還有可能:'prop((s:String)=> echo(s)必須是equals(s))。setGen(Gen.oneOf(strings:_ *))' – Eric

+0

再次感謝。如上所示,它真的比'strings foreach {s => echo(s)must equal to(s)}'更好嗎? – Michael