我发现Hamcrest与JUnit一起使用很方便。现在我将使用ScalaTest。我知道我可以使用Hamcrest,但我想知道我是否真的应该使用。ScalaTest没有提供类似的功能吗?还有其他Scala库(matchers)吗?
人们使用Hamcrest和ScalaTest吗?
发布于 2015-08-22 14:39:11
正如迈克尔所说,您可以使用标量测试匹配器。只需确保在测试类中扩展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模式匹配,断言什么可以/不能编译,.)
发布于 2013-07-14 05:24:22
Scalatest有内置的火柴。此外,我们使用期待。在某些情况下,它比matcher更简洁和灵活(但是它使用宏,所以它至少需要2.10版本的Scala)。
发布于 2014-02-19 22:04:00
不,你不需要ScalaTest的Hamcrest。只需将ShouldMatchers或MustMatchers特性与您的规格相混合即可。Must和Should匹配器的区别在于,在断言中只使用must而不是should。
示例:
class SampleFlatSpec extends FlatSpec with ShouldMatchers {
// tests
}https://stackoverflow.com/questions/17636640
复制相似问题