Geb& Spock - If / Then / Else逻辑 - 如何检查记录并执行一项操作(如果存在)但如果不存在则继续 [英] 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't

查看:454
本文介绍了Geb& Spock - If / Then / Else逻辑 - 如何检查记录并执行一项操作(如果存在)但如果不存在则继续的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm testing the creation and then removal of a record on my site using Geb/Spock. However I can't create the record if it already exists and so I check for the existence of the record and remove it if it exists in the beginning of the test. The problem occurs when the record does not exist, causing the test to fail. Is there a way to incorporate some if/then/else logic so the test will continue if it does not find the record in the beginning and remove it if it does find it?

编辑示例代码:

/**
 * 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'() {}


推荐答案

您可以执行以下操作:

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

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

如果没有显示记录(999)那么!显示语句将评估为true,因此不应评估 deleteRecord(999).click(),因此导致测试通过。

If record(999) isn't displayed then the !displayed statement will evaluate to true, and so the deleteRecord(999).click() shouldn't get evaluated, therefore causing the test to pass.

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

When the record is displayed, !displayed will evaluate to false, and so spock will have to evaluate the deleteRecord(999).click() statement, providing the desired behavior.

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

This works based on short-circuit evaluation (which Java and Groovy both use) http://en.wikipedia.org/wiki/Short-circuit_evaluation

这篇关于Geb& Spock - If / Then / Else逻辑 - 如何检查记录并执行一项操作(如果存在)但如果不存在则继续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆