Hamcrest and ScalaTest

10
我发现在使用JUnit时,Hamcrest很方便。现在我将使用ScalaTest。我知道可以使用Hamcrest,但我想知道是否真的需要。不是ScalaTest提供了类似的功能吗?还有其他用于此目的(匹配器)的Scala库吗?
人们会在ScalaTest中使用Hamcrest吗?

1
我不能针对这个特定问题发表意见,但是根据我的一般经验,我发现旨在提供表达能力的Java库通常被Scala库(或仅仅是Scala语言特性)所取代。 - Chris Martin
3个回答

4
如Michael所说,你可以使用ScalaTest的匹配器。只需确保在测试类中扩展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模式匹配,断言哪些内容可以/不可以编译,...)


3

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


1
不,你不需要在ScalaTest中使用Hamcrest。只需在你的Spec中混入ShouldMatchersMustMatchers trait即可。 MustShould匹配器之间的区别在于,在断言中你只需使用must而不是should
例子:
class SampleFlatSpec extends FlatSpec with ShouldMatchers {
     // tests
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接