Hamcrest and ScalaTest

I found Hamcrest convenient to use with JUnit . Now I will use ScalaTest . I know I can use Hamcrest , but I wonder if this is really needed. Does ScalaTest similar functionality? Is there any other Scala library for this purpose (mapping)?

Do people Hamcrest with ScalaTest ?

+6
source share
3 answers

Scalatest has built-in matchers . We also use expecty . In some cases, it is more concise and flexible than helpers (but it uses macros, so it requires at least a 2.10 version of Scala).

+3
source

As Michael said, you can use ScalaTest matchers . Just make sure you extend Matchers in the test class. They can very well replace Hamcrest functionality, use Scala functions and look more natural in Scala for me.

Here you can compare the combinations of Hamcrest and ScalaTest with a few examples:

 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 much more you can do with ScalaTest (for example, use Scala pattern matching, say that it can / cannot compile, ...)

+2
source

No, you do not need Hamcrest with ScalaTest. Just mix in the ShouldMatchers or MustMatchers with your Spec. The difference between Must and Should is just to use Must instead of Should in statements.

Example:

 class SampleFlatSpec extends FlatSpec with ShouldMatchers { // tests } 
+1
source

Source: https://habr.com/ru/post/949392/


All Articles