像Scala中的“Power assert”类似于Groovy?

时间:2016-03-22 23:14:00

标签: scala groovy assert scalatest

我想知道是否有什么能给我的结果类似于Groovy的强大断言声明。

> assert ["1", '2']*.size() == [2, 3]

Result: Assertion failed: 

assert ["1", '2']*.size() == [2, 3]
                   |      |
                   [1, 1] false

AFAIK既不支持语言,也不支持 scalatest,我目前正在使用它。 但也许有人可以建议一些侧库这样做?这是一个宠物项目,所以实验性和不受支持的库很好。

编辑:我知道匹配器(scalatest,甚至是普通的java hamcrest匹配器)。我发现它们写得很冗长,而且它们的输出缺乏细节。

上面的例子显示了中间计算步骤,便于检测错误。它会向您展示测试代码的详细信息。

我希望,引入此类行为需要在运行时获得有关表达式AST的信息。但我想,这些信息可以通过使用宏来“烘焙”编译时间。

即。如果我们有表达式assert a + b == c scala(或者我正在寻找的一些宏扩展名)可以将其重写为:

if (!(a + b == c)) {
  // detailed message is
  // compute a
  // compute b
  // compute a + b
  // compute c
  // compute a + b == c
  // Make it pretty.

  throw new AssertionFailedException(prettyDetailedMessage)
}

所以我在看它是否已经实施,如果是的话 - 在哪里。

3 个答案:

答案 0 :(得分:4)

在ScalaTest中,您可以使用DiagrammedAssertions。 见http://www.scalatest.org/release_notes/2.2.0#diagrammedAssertions

这是基于Expecty,它是Spock的电源断言的基于宏的实现。见https://github.com/pniederw/expecty

答案 1 :(得分:2)

Specs2匹配器可以很好地处理错误消息:

class Specs2Specification extends Specification {
  "specs2 assertion" should {
    "fail" in {
      List("1", "2").map(_.length) must_=== List(2, 3)
    }  
  }
}

运行输出:

[info] Specs2Specification
[info]
[info] specs2 assertion should
[error]   x fail
[error]    List(1, 1) is not equal to List(2, 3) 
[info]
[error] Added (2)
[error] 1
[error] 1
[info]
[error] Missing (2)
[error] 2
[error] 3

List("1", "2").map(_.length) must contain(exactly(2, 3)).inOrder

产生

[error]   x fail
[error]    the values 2, 3 are not in order 

lots of them,您可以创建自定义的。

答案 2 :(得分:0)

您的groovy代码段实际上已翻译为以下scala代码(假设您已使用scalatest):

assert((List("1", "2") map (_.length)) === List(2, 3))

它会产生以下错误消息:

*** FAILED ***
List(1, 1) did not equal List(1, 3)