简体   繁体   English

Hamcrest和ScalaTest

[英]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模式匹配,断言什么可以/不能编译,......)

Scalatest has build-in matchers . Scalatest有内置匹配器 Also we use expecty . 我们也使用expecty In some cases it's more concise and flexible than matchers (but it uses macros, so it requires at least 2.10 version of Scala). 在某些情况下,它比匹配器更简洁和灵活(但它使用宏,因此它需要至少2.10版本的Scala)。

No, you don't need Hamcrest with ScalaTest. 不,你不需要使用ScalaTest的Hamcrest。 Just mix in the ShouldMatchers or MustMatchers trait with your Spec. 只需将ShouldMatchersMustMatchers特性与您的Spec混合即可。 The difference between Must and Should matchers is you simply use must instead of should in assertions. 之间的差异MustShould匹配器是您只需使用must的,而不是should在断言。

Example: 例:

class SampleFlatSpec extends FlatSpec with ShouldMatchers {
     // tests
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM