10

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?

Michael
  • 41,026
  • 70
  • 193
  • 341
  • 1
    I can't speak for this particular question, but: In my general experience, I find that Java libraries aiming to provide expressiveness are usually obviated by Scala libraries (or simply by Scala language features). – Chris Martin Jul 14 '13 at 05:30

3 Answers3

4

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

Mifeet
  • 12,949
  • 5
  • 60
  • 108
3

Scalatest has build-in matchers. Also we use 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).

Sergey Passichenko
  • 6,920
  • 1
  • 28
  • 29
1

No, you don't need Hamcrest with ScalaTest. Just mix in the ShouldMatchers or MustMatchers trait with your Spec. The difference between Must and Should matchers is you simply use must instead of should in assertions.

Example:

class SampleFlatSpec extends FlatSpec with ShouldMatchers {
     // tests
}
tomrozb
  • 25,773
  • 31
  • 101
  • 122