user2241239
user2241239

Reputation:

How to match type of instance in ScalaTest

I was trying to assert exception type in a test using Matchers (don't ask why) and the solution that I got is this:

exception.getClass shouldBe classOf[FileNotFoundException]

But it looks super ugly, is there a better way?

Bye

Upvotes: 3

Views: 1087

Answers (2)

marios
marios

Reputation: 8996

You can you the "an [] should be thrownBy" matcher:

 an [IllegalArgumentException] should be thrownBy {
    //code that should raise an exception here
 }

Make sure your test class includes the "Matchers":

class MyTestClass extends FunSuite with Matchers 

Upvotes: 1

Paweł Jurczenko
Paweł Jurczenko

Reputation: 4471

One possible solution would be to use intercept method:

val exception = intercept[NoSuchElementException] {
  List.empty[String].head // Code that throws exception
}

exception.getMessage shouldBe "head of empty list"

Upvotes: 1

Related Questions