2013-07-14 15 views
6

Ho trovato Hamcrest comodo da utilizzare con JUnit. Ora userò lo ScalaTest. So che posso usare Hamcrest ma mi chiedo se davvero io dovrei. ScalaTest non fornisce funzionalità simili? C'è qualche altra libreria di Scala a tale scopo (matcher)?Hamcrest e ScalaTest

Le persone usano Hamcrest con ScalaTest?

+1

Non posso parlare per questa particolare domanda, ma: Nella mia esperienza generale, trovo che le librerie Java che mirano a fornire espressività sono di solito ovviate dalle librerie Scala (o semplicemente dalle caratteristiche del linguaggio Scala). –

risposta

3

Scalatest ha incorporato matchers. Inoltre usiamo expecty. In alcuni casi è più conciso e flessibile dei corrispondenti (ma usa macro, quindi richiede almeno la versione 2.10 di Scala).

1

No, non è necessario Hamcrest con ScalaTest. Basta mescolare il tratto ShouldMatchers o MustMatchers con la tua Spec. La differenza tra gli equivalenti Must e Should è semplicemente utilizzare must anziché should nelle affermazioni.

Esempio:

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

Come Michael, ha detto, è possibile utilizzare ScalaTest's matchers. Assicurati di estendere lo Matchers nella tua classe di test. Possono benissimo sostituire la funzionalità di Hamcrest, sfruttare le funzionalità di Scala e sembrare più naturale in Scala per me.

Qui, è possibile confrontare Hamcrest e ScalaTest matchers su alcuni esempi:

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)) 

... e molto di più si può fare con ScalaTest (ad esempio, utilizzare pattern matching Scala, affermare ciò che può/non può compilare , ...)

Problemi correlati