Geb & Spock - If/Then/Else 逻辑 - 如何检查记录并在存在时执行一件事,但如果不存在则继续执行

1 testing logic if-statement spock geb

我正在使用 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'() {}
Run Code Online (Sandbox Code Playgroud)

jk4*_*k47 5

你可以这样做:

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

then: 'remove record 999'
!displayed || deleteRecord(999).click()
Run Code Online (Sandbox Code Playgroud)

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

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

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