Groovy Power Assert语句输出



我正在使用Spock,讨厌功能测试的硬断言。我已经编写了一个SoftAssert类,并且一切正常,我只想让它看起来更像Groovy的power assert。

这是我现有的方法:

public void verifyEquals(def expected, def actual, String message = '') {
    try {
        assert expected == actual
    } catch (AssertionError e) {
        LOGGER.warn("Verification failed, expected: ${expected.toString()} but got ${actual}.n ${message}")
        softAssertList.add(new SoftAssert(message, e))
    }
}

我只是发现了失败,很简单。现在缺少的是Groovy做得这么好的漂亮输出。而不是我传递给verifyEquals的语句,例如:verifyEquals(8, (3 + x) * z)

8 == (3 + x) * z
  |     | |  | |
  |     | 0  | |
  |     3    | 2
  |          6
false

我得到expected == actual

expected == actual
   |     |    |
   8     |    6
       false

之所以会发生这种情况,是因为语句是在将其传递到方法之前进行计算的。有人知道如何在传递参数时保持测试为verifyEquals(8, (3 + x) * z)格式吗?以及如何保持Power Assert错误与原始参数不同?

verify方法应该接受包含断言的Closure(代码块(,执行它,并存储抛出的任何异常。用法如下:verify { assert 8 == (3 + x) * z }

如果使用Spock的@ConditionBlock注释对方法进行注释,并将其放在Spock在编译时可以找到的位置(例如基类(,则assert关键字甚至可以省略。

请注意,Spock的条件与Groovy的幂断言不同。如果您捕获Spock的ConditionNotSatisfiedError,您将获得有关断言的进一步信息(例如,完整的语法树(,您可以利用它来提供更好的反馈。如果您不需要这些附加信息,那么捕获AssertionError就可以了。

也许我的答案有点偏离主题,但这个问题最接近我在这里搜索的内容,我想分享我自己的发现。我发现这个模式在使用Spock:时非常有用

try {
  assert myPage.myField.text() == "field valueXXX"
}
catch (ConditionNotSatisfiedError e) {
  // Enrich Groovy PowerAssertion with additional text
  def condition = e.condition
  throw new ConditionNotSatisfiedError(
    new Condition(
      condition.values,
      condition.text,
      condition.position,
      "Attention, the Selenium driver obviously cannot delete the session cookie " +
        "JSESSIONID_MY_PROJECT because of 'http-only'!n" +
        "Please deploy my.project.mobile.smoke instead of my.project.mobile."
    )
  )
}

错误日志如下所示:

Condition not satisfied:
myPage.myField.text() == "field value"
|         |       |      |
|         |       |      false
|         |       |      3 differences (78% similarity)
|         |       |      field value(---)
|         |       |      field value(XXX)
|         |       field valueXXX
|         myField - SimplePageContent (owner: my.project.module.geb.pages.MyPage, args: [], value: null)
my.project.module.AdminPage
Attention, the Selenium driver obviously cannot delete the session cookie JSESSIONID_MY_PROJECT because of 'http-only'!
Please deploy my.project.mobile.smoke instead of my.project.mobile.
Expected :field valueXXX
Actual   :field value
  <Click to see difference>
    at my.project.module.MySampleIT.#testName(MySampleIT.groovy:57)

最新更新