[英]Hamcrest and ScalaTest
我发现Hamcrest
很方便与JUnit
一起使用。 现在我将使用ScalaTest
。 我知道我可以使用Hamcrest
但我想知道我是否应该这样做 。 ScalaTest
不提供类似的功能吗? 是否有任何其他Scala库用于此目的(匹配器)?
人们在ScalaTest
使用Hamcrest
吗?
正如迈克尔所说,你可以使用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模式匹配,断言什么可以/不能编译,......)
不,你不需要使用ScalaTest的Hamcrest。 只需将ShouldMatchers
或MustMatchers
特性与您的Spec混合即可。 之间的差异Must
和Should
匹配器是您只需使用must
的,而不是should
在断言。
例:
class SampleFlatSpec extends FlatSpec with ShouldMatchers {
// tests
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.