bfb
bfb

Reputation: 447

How to test for two or more exceptions in ScalaTest?

I am using ScalaTest for unit testing. I currently have the following:

f(x) should produce[Exception]

I would like to specify two or more subclasses of Exception, e.g.

f(x) should (produce[ExceptionA] or produce[ExceptionB])

Is this possible? If not, what is the recommended way to proceed?

Upvotes: 1

Views: 128

Answers (1)

mikej
mikej

Reputation: 66263

I would look at restructuring either your code or your tests if you've got a block of code that is non-deterministic in the exception that it will throw. That said, you could use an evaluating block to capture the thrown exception and then check if it's one of the required types. e.g.

val caught = evaluating {
  // code that should throw an exception
} should produce [Exception]

then

assert(caught.isInstanceOf[ExceptionA] || caught.isInstanceOf[ExceptionB])

Upvotes: 3

Related Questions