Search code examples
scalascalatest

Or operator with scalaTest matcher


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.


Solution

  • 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