3

Using scalatest idiomatic matcher how can I check if a class is instance of A or B?

I try with or but it does not work

e shouldBe a [ChannelWriteException] || e shouldBe a [ConnectException]

Here How to do an instanceof check with Scala(Test) explain how to use isInstanceOf, but not how to make an or Regards.

Community
  • 1
  • 1
paul
  • 12,873
  • 23
  • 91
  • 153
  • I base my question in that question http://stackoverflow.com/questions/8561898/how-to-do-an-instanceof-check-with-scalatest but there they dont specify how to make an "or" which is what my question it´s about – paul May 17 '17 at 11:44
  • Possible duplicate of [How to do an instanceof check with Scala(Test)](http://stackoverflow.com/questions/8561898/how-to-do-an-instanceof-check-with-scalatest) – jwvh May 17 '17 at 18:17

1 Answers1

4

you can use Matcher#should(Matcher[T]) with Matcher#or[U <: T](Matcher[U])

example,

  it("test instanceOf A or B") {
    val actual = new Thread()
    actual should (be (a [RuntimeException]) or be (a [Thread]))
  }

if actual does not match the expected, it errors out with proper messaging,

  it("test instanceOf A or B") {
    val actual = new String()
    actual should (be (a [RuntimeException]) or be (a [Thread]))
  }

error

"" was not an instance of java.lang.RuntimeException, but an instance of java.lang.String, and 
"" was not an instance of java.lang.Thread, but an instance of java.lang.String

The conventional way, (I'm still in 2000s)

val actual = new Thread()
assert(actual.isInstanceOf[RuntimeException] || actual.isInstanceOf[Thread])

Reference

http://www.scalatest.org/user_guide/using_matchers#logicalExpressions

Is there anyway we can give two conditions in Scalatest using ShouldMatchers

Community
  • 1
  • 1
prayagupa
  • 30,204
  • 14
  • 155
  • 192
  • I find I need some extra brackets. But basically the same `actual should (be(a[RuntimeException])).or(be(a[Thread]))` – Stephen May 17 '17 at 10:53