我目前正在尝试为 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/