或带有 scalaTest 匹配器的运算符

Or operator with scalaTest matcher

如何使用 scalatest 惯用匹配器检查 class 是 A 还是 B 的实例?

我尝试使用 or 但它不起作用

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

这里 How to do an instanceof check with Scala(Test) 解释如何使用 isInstanceOf,但不解释如何使用 or 问候。

您可以将 Matcher#should(Matcher[T])Matcher#or[U <: T](Matcher[U])

一起使用

示例,

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

如果实际情况与预期不符,则会通过正确的消息传递出错,

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

错误

"" 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

常规方式,(我还在2000年代

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

参考

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