【问题标题】:Hamcrest and ScalaTestHamcrest 和 ScalaTest
【发布时间】:2013-07-14 04:55:09
【问题描述】:

我发现HamcrestJUnit 一起使用很方便。现在我将使用ScalaTest。我知道我可以使用Hamcrest,但我想知道我是否真的应该ScalaTest 不提供类似的功能吗?是否有任何其他 Scala 库用于此目的(匹配器)?

人们是否将HamcrestScalaTest 一起使用?

【问题讨论】:

  • 我不能说这个特定的问题,但是:根据我的一般经验,我发现旨在提供表现力的 Java 库通常被 Scala 库(或简单地被 Scala 语言特性)所排除。

标签: unit-testing scala hamcrest


【解决方案1】:

正如迈克尔所说,您可以使用ScalaTest's matchers。只要确保你在你的测试类中扩展Matchers。它们可以很好地替换 Hamcrest 的功能,利用 Scala 特性,并且在我看来在 Scala 中更自然。

在这里,您可以通过几个示例比较 Hamcrest 和 ScalaTest 匹配器:

val x = "abc"
val y = 3
val list = new util.ArrayList(asList("x", "y", "z"))
val map = Map("k" -> "v")

// equality
assertThat(x, is("abc")) // Hamcrest
x shouldBe "abc"         // ScalaTest

// nullity
assertThat(x, is(notNullValue()))
x should not be null

// string matching
assertThat(x, startsWith("a"))
x should startWith("a")
x should fullyMatch regex "^a..$" // regex, no native support in Hamcrest AFAIK

// type check
assertThat("a", is(instanceOf[String](classOf[String])))
x shouldBe a [String]

// collection size
assertThat(list, hasSize(3))
list should have size 3

// collection contents
assertThat(list, contains("x", "y", "z"))
list should contain theSameElementsInOrderAs Seq("x", "y", "z")

// map contents
map should contain("k" -> "v") // no native support in Hamcrest

// combining matchers
assertThat(y, both(greaterThan(1)).and(not(lessThan(3))))
y should (be > (1) and not be <(3))

...以及您可以使用 ScalaTest 做的更多事情(例如,使用 Scala 模式匹配,断言可以/不能编译的内容,...)

【讨论】:

    【解决方案2】:

    Scalatest 内置了matchers。我们也使用expecty。在某些情况下,它比匹配器更简洁灵活(但它使用宏,因此至少需要 2.10 版本的 Scala)。

    【讨论】:

      【解决方案3】:

      不,您不需要带有 ScalaTest 的 Hamcrest。只需将 ShouldMatchersMustMatchers 特征与您的 Spec 混合。 MustShould 匹配器之间的区别在于您只需在断言中使用 must 而不是 should

      例子:

      class SampleFlatSpec extends FlatSpec with ShouldMatchers {
           // tests
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-09
        • 2016-06-02
        • 1970-01-01
        相关资源
        最近更新 更多