簡體   English   中英

使用Monoid進行簡單的單元測試

[英]Simple unit testing with monoids

假設我測試一個函數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真的必要嗎? 我可以不使用 monoid刪除上面的樣板代碼嗎?

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

您也可以使用ScalaCheck

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM