Hamcrest and ScalaTest

hamcrest, scala, unit-testing

Solution

As Michael said, you can use ScalaTest's matchers. Just make sure you extend `Matchers` in your test class. They can very well replace functionality of Hamcrest, leverage Scala features and look more natural in Scala to me.

Here, you can compare Hamcrest and ScalaTest matchers on 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 a lot more you can do with ScalaTest (e.g. use Scala pattern matching, assert what can/cannot compile, ...)

Problem

I found `Hamcrest` convenient to use with `JUnit`. Now I am going to use `ScalaTest`. I know I can use `Hamcrest` but I wonder if I really should. Does not `ScalaTest` provide similar functionality ? Is there any other Scala library for that purpose (matchers) ? Do people use `Hamcrest` with `ScalaTest`?

Original source