只有第一个测试成功 运行 Spock suite with setupSpec()

Only first test succeeds running Spock suite with setupSpec()

我一直在试验 Geb/Spock 来测试一些 Web 应用程序,但遇到了一个我似乎无法弄清楚的问题。

我有一个测试 class 有一个 setupSpec() fixture 方法调用 AuthenticationSpec 中定义的登录方法,然后是一堆其他方法断言此页面上的各种内容:

class TestThisPage extends AuthenticationSpec {
    def setupSpec() {
        loginComplete("some user ID", "some password")
        assert page instanceof ThisPage
    }

    def "Verify some link's text is correct"() {
        when: "The user is at this page"

        then: "The this specific link's text is correct"
        assert  someLink.text().equalsIgnoreCase("I am some text")
    }

    def "Verify that the correct user name is displayed"() {
        when: "The user is signed in and at this page"

        then: "The signed-in user's display name appears correctly on the page"
        assert signInText.equalsIgnoreCase("Signed in as: some user ID")
    }

    def "Verify this page's copyright"() {
        when: "The user is redirected to this page"

        then: "The copyright is correct"
        assert legalInfo.text().trim().equalsIgnoreCase("Some copyright text here")
    }
}

现在当我 运行 TestThisPage 作为测试套件时,只有第一个测试用例(在 setupSpec() 方法之后)通过,其余的都失败了:groovy.lang.MissingPropertyException: Unable to resolve <some content identifier specified on ThisPage>

我知道我的内容定义正确:

class ThisPage extends Page {

    static at = {
        title == "This page"
    }
    static content = {
        someLink(to: SomeOtherPage) {$("a[href='someOtherPage.jsp'")}
        signInText  {loginInfo.find("#static-label").text().trim()}
    }
}

而且我可以切换测试方法的顺序,第一个总是会通过,即使最后一个 运行 失败了。如果我 运行 这些测试方法作为一个单元测试,它们也都通过了。

我让它工作的唯一方法是将 at ThisPage 添加到 when 或 given 块。我想在每个测试方法中将页面显式设置为 ThisPage 是有意义的,但是为什么当 运行 将整个 class 作为测试套件时,只有第一个测试方法通过(即使没有at ThisPage)?

每个后续测试方法都不知道您所在的页面。

您可以创建页面的共享实例,然后您的每个测试都可以在同一规范中访问该实例:

class TestThisPage extends AuthenticationSpec {

    @Shared ThisPage thisPage

    def setupSpec() {
        thisPage = loginComplete("some user ID", "some password")
        assert page instanceof ThisPage
    }

    def "Verify some link's text is correct"() {
        when: "The user is at this page"

        then: "The this specific link's text is correct"
        assert  thisPage.someLink.text().equalsIgnoreCase("I am some text")
    }

    def "Verify that the correct user name is displayed"() {
        when: "The user is signed in and at this page"

        then: "The signed-in user's display name appears correctly on the page"
        assert thisPage.signInText.equalsIgnoreCase("Signed in as: some user ID")
    }

    def "Verify this page's copyright"() {
        when: "The user is redirected to this page"

        then: "The copyright is correct"
        assert thisPage.legalInfo.text().trim().equalsIgnoreCase("Some copyright text here")
    }
}