Groovy Power断言语句输出

Groovy Power断言语句输出,groovy,assert,Groovy,Assert,我使用Spock和hate硬断言进行功能测试。我已经编写了一个SoftAssert类,并且一切正常,我只是想让它看起来更像Groovy的power asserts 以下是我现有的方法: public void verifyEquals(def expected, def actual, String message = '') { try { assert expected == actual } catch (AssertionError e) {

我使用Spock和hate硬断言进行功能测试。我已经编写了一个SoftAssert类,并且一切正常,我只是想让它看起来更像Groovy的power asserts

以下是我现有的方法:

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)

我得到
expected==actual

expected == actual
   |     |    |
   8     |    6
       false

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

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

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


请注意,Spock的条件与Groovy的power断言不同。如果捕获Spock的
条件NotSatisfiederRor
,您将获得有关断言的更多信息(例如完整语法树),您可以利用这些信息提供更好的反馈。如果您不需要这些附加信息,那么捕获断言错误就可以了。

也许我的答案有点离题,但这个问题与我在这里搜索的内容最接近,我想分享我自己的发现。在使用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."
    )
  )
}
错误日志如下所示:

条件不满足:
myPage.myField.text()=“字段值”
|         |       |      |
|| |假
|| | 3差异(78%相似性)
|| |字段值(---)
|| |字段值(XXX)
||字段值XXX
|myField-SimplePageContent(所有者:my.project.module.geb.pages.MyPage,参数:[],值:null)
my.project.module.AdminPage
注意,由于“仅限http”,Selenium驱动程序显然无法删除会话cookie JSSessionID_MY_项目!
请部署my.project.mobile.smoke而不是my.project.mobile。
预期值:字段值XXX
实际值:字段值
在my.project.module.MySampleIT.#testName(MySampleIT.groovy:57)上

完美答案。非常感谢。
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."
    )
  )
}