【问题标题】:running same tests for different classes in groovy and spock在 groovy 和 spock 中为不同的类运行相同的测试
【发布时间】:2013-04-06 02:00:51
【问题描述】:

我目前正在尝试为 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 中的所有测试?如何正确实例化设置?我希望我是清楚的。

【问题讨论】:

    标签: unit-testing testing groovy tdd spock


    【解决方案1】:

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

    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
    }
    

    【讨论】:

    • 很好的答案。非常适合我。我正在测试一个数据结构库,其中我正在执行类似结构、列表、堆栈、队列的多个实现,这为我节省了数百行重复代码,因为我可以通过这种方法测试所有常见的属性。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    • 1970-01-01
    • 2016-07-13
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    相关资源
    最近更新 更多