2013-07-14 47 views
6

我發現Hamcrest方便與JUnit使用。現在我要使用ScalaTest。我知道我可以使用Hamcrest但我不知道我是否真的應該ScalaTest是否提供類似的功能?有沒有其他的Scala庫(Matchers)?Hamcrest和ScalaTest

人們是否會使用HamcrestScalaTest

+1

我不能爲這個特殊的問題發言,但:在我的一般經驗,我發現,旨在提供表現Java庫通常是由斯卡拉庫消除(或僅僅是Scala語言功能)。 –

回答

3

Scalatest具有內置的matchers。我們也使用expecty。在某些情況下,它比匹配器更簡潔靈活(但它使用宏,所以它至少需要2.10版Scala)。

1

不,你不需要用ScalaTest測試Hamcrest。只需在規格中混入ShouldMatchersMustMatchers特質。 MustShould匹配器之間的區別是,您只需使用must而不是should進行斷言。

例子:

class SampleFlatSpec extends FlatSpec with ShouldMatchers { 
    // tests 
} 
2

正如邁克爾說,你可以使用ScalaTest's matchers。只要確保在測試課程中擴展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的模式匹配,斷言什麼可以/不可以編譯,...)