unit-testing - 在 groovy 和 spock 中为不同的类运行相同的测试

标签 unit-testing testing groovy tdd spock

我目前正在尝试为 2 个不同的类运行相同的测试用例,但 setup() 有问题,我看到了类似的问题,但还没有看到使用 Spock 进行 groovy 测试的解决方案,我还没有能够弄清楚。

所以我本质上是使用两种不同的方法解决同一个问题,所以相同的测试用例应该适用于两个类,我试图保持不要重复自己(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 中的所有测试?如何正确实例化设置?我希望我说清楚了。

最佳答案

忘记 Controller 设置吧。当您执行具体类的测试时,来自父类(super class)的所有测试将自动执行。例如

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
}

关于unit-testing - 在 groovy 和 spock 中为不同的类运行相同的测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15846207/

相关文章:

javascript - 如何让 QUnit 在异常时打印回溯?

android - sonarqube 具有 android 测试和测试覆盖率

testing - Google firebase 测试实验室,兼容性测试

testing - 如何使用 WebDriver 单击元素

groovy - 如何使任务调用主类

python - 如何测试django中的编辑功能? (错误 django.db.utils.IntegrityError : NOT NULL constraint failed)

python - AttributeError : <module '__main__' from [. .] 没有属性 'open'

scala - 找不到用于测试的现有数据 Scala Specs2

groovy - @CompileStatic 用于普通 Groovy 脚本

grails - Grails在对象引用上设置元类属性