【问题标题】:Geb & Spock - If/Then/Else logic - How to check for a record and do one thing if it exists but continue on if it doesn'tGeb & Spock - If/Then/Else 逻辑 - 如何检查记录并在存在时执行一件事,如果不存在则继续
【发布时间】:2014-08-18 16:39:12
【问题描述】:

我正在使用 Geb/Spock 在我的网站上测试记录的创建和删除。但是,如果它已经存在,我将无法创建记录,因此我检查记录是否存在,如果它在测试开始时存在,则将其删除。当记录不存在时会出现问题,导致测试失败。有没有办法合并一些 if/then/else 逻辑,这样如果在开始时没有找到记录,测试将继续,如果找到则将其删除?

编辑示例代码:

/**
 * Integration test for Create Record
**/
class CreateAndRemoveRecordSpec extends GebSpec {

def 'check to make sure record 999 does not exist'() {

    given: 'user is at Account Page'
    to MyAccountPage

    when: 'the user clicks the sign in link'
    waitFor { header.signInLink.click() }

    and: 'user logs on with credentials'
    at LoginPage
    loginWith(TEST_USER)

    then: 'user is at landing page.'
    at MyAccountPage

    and: 'list of saved records is displayed'
    myList.displayed

    /* I would like some sort of if here so the test doesn't fail if there is no record*/
    when: 'record 999 exists'
    record(999).displayed

    then: 'remove record 999'
    deleteRecord(999).click()

    /* continue on with other tests without failing whether or not the record exists */
}

def 'test to create record 999'() {}

def 'test to remove record 999'() {}

【问题讨论】:

  • 没有一些代码很难说,但是如果记录不存在,你能捕捉到异常吗?
  • 添加了一些 Geb Spock 代码,以便更好地了解我正在尝试做的事情。
  • record 是什么类?
  • 你能做类似when: \ record(999).displayed\ then:\ def e = thrown(SomeException)的事情吗
  • 在使用 sql 运行测试之前可以删除记录吗?

标签: testing if-statement logic spock geb


【解决方案1】:

你可以这样做:

when: 'record 999 exists'
def displayed = record(999).displayed

then: 'remove record 999'
!displayed || deleteRecord(999).click()

如果 record(999) 未显示,则 !displayed 语句将评估为 true,因此不应评估 deleteRecord(999).click(),从而导致测试通过。

当显示记录时,!displayed 将评估为 false,因此 spock 必须评估 deleteRecord(999).click() 语句,以提供所需的行为。

这基于短路评估(Java 和 Groovy 都使用)http://en.wikipedia.org/wiki/Short-circuit_evaluation

【讨论】:

  • 这有点小技巧,同样使用displayed && deleteRecord(999).click() 可能比使用|| 更有意义,但这只是偏好!
  • 我会说'&&'更强大:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-25
相关资源
最近更新 更多