【问题标题】:Or operator with scalaTest matcher或带有 scalaTest 匹配器的运算符
【发布时间】:2017-10-16 17:19:34
【问题描述】:

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

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

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

这里How to do an instanceof check with Scala(Test)解释如何使用isInstanceOf,而不是如何制作一个或 问候。

【问题讨论】:

标签: scala scalatest


【解决方案1】:

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

【讨论】:

  • 我发现我需要一些额外的括号。不过基本一样actual should (be(a[RuntimeException])).or(be(a[Thread]))
猜你喜欢
  • 2016-02-12
  • 1970-01-01
  • 2018-06-05
  • 1970-01-01
  • 1970-01-01
  • 2012-01-25
  • 1970-01-01
  • 1970-01-01
  • 2016-05-14
相关资源
最近更新 更多