0

我目前正在尝试为 2 个不同的类运行相同的测试用例,但是 setup() 有问题,我看到了类似的问题,但还没有看到使用 Spock 进行常规测试的解决方案,而且我无法想办法。

所以我本质上是使用 2 种不同的方法来解决相同的问题,所以相同的测试用例应该适用于两个类,我试图保持不要重复自己(DRY)。

因此,我将 MainTest 设置为抽象类,将 MethodOneTest 和 MethodTwoTest 设置为扩展抽象 MainTest 的具体类:

import spock.lang.Specification
abstract class MainTest extends Specification {
    private def controller

    def setup() {
        // controller = i_dont_know..
    }

    def "test canary"() {
        expect:
        true
    }

    // more tests
}

我的具体课程是这样的:

class MethodOneTest extends MainTest {
    def setup() {
        def controller = new MethodOneTest()
    }
}

class MethodTwoTest extends MainTest {
    def setup() {
        def controller = new MethoTwoTest()
    }
}

那么有谁知道我如何从我的具体类 MethodOneTest 和 MethodTwoTest 中运行抽象 MainTest 中的所有测试?如何正确实例化设置?我希望我很清楚。

4

1 回答 1

2

忘记控制器设置。当您为具体类执行测试时,将自动执行来自超类的所有测试。例如

import spock.lang.Specification
abstract class MainTest extends Specification {
    def "test canary"() {
        expect:
        true
    }

    // more tests
}

class MethodOneTest extends MainTest {

    // more tests
}

class MethodTwoTest extends MainTest {

    // more tests
}

但它应该有意义多次运行相同的测试。所以用一些东西来参数化它们是合理的,例如一些类实例:

import spock.lang.Specification
abstract class MainSpecification extends Specification {
    @Shared 
    protected Controller controller

    def "test canary"() {
        expect:
        // do something with controller
    }

    // more tests
}

class MethodOneSpec extends MainSpecification {
    def setupSpec() {
        controller = //... first instance
    }

    // more tests
}

class MethodTwoSpec extends MainSpecification {
    def setupSpec() {
        controller = //... second instance
    }

    // more tests
}
于 2013-04-06T08:42:35.157 回答