[英]Hamcrest and ScalaTest
I found Hamcrest
convenient to use with JUnit
. 我发现
Hamcrest
很方便与JUnit
一起使用。 Now I am going to use ScalaTest
. 现在我将使用
ScalaTest
。 I know I can use Hamcrest
but I wonder if I really should . 我知道我可以使用
Hamcrest
但我想知道我是否应该这样做 。 Does not ScalaTest
provide similar functionality ? ScalaTest
不提供类似的功能吗? Is there any other Scala library for that purpose (matchers) ? 是否有任何其他Scala库用于此目的(匹配器)?
Do people use Hamcrest
with ScalaTest
? 人们在
ScalaTest
使用Hamcrest
吗?
As Michael said, you can use ScalaTest's matchers . 正如迈克尔所说,你可以使用ScalaTest的匹配器 。 Just make sure you extend
Matchers
in your test class. 只需确保在测试类中扩展
Matchers
。 They can very well replace functionality of Hamcrest, leverage Scala features and look more natural in Scala to me. 它们可以很好地取代Hamcrest的功能,利用Scala功能,并在Scala中看起来更自然。
Here, you can compare Hamcrest and ScalaTest matchers on a few examples: 在这里,您可以通过以下几个示例来比较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))
... and a lot more you can do with ScalaTest (eg use Scala pattern matching, assert what can/cannot compile, ...) ...还有更多你可以用ScalaTest做的事情(例如使用Scala模式匹配,断言什么可以/不能编译,......)
No, you don't need Hamcrest with ScalaTest. 不,你不需要使用ScalaTest的Hamcrest。 Just mix in the
ShouldMatchers
or MustMatchers
trait with your Spec. 只需将
ShouldMatchers
或MustMatchers
特性与您的Spec混合即可。 The difference between Must
and Should
matchers is you simply use must
instead of should
in assertions. 之间的差异
Must
和Should
匹配器是您只需使用must
的,而不是should
在断言。
Example: 例:
class SampleFlatSpec extends FlatSpec with ShouldMatchers {
// tests
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.