或者使用scalaTest匹配器的运算符

时间:2017-05-17 09:57:54

标签: scala scalatest

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

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

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

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

1 个答案:

答案 0 :(得分:3)

您可以将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

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