我的 Groovy/Spock 单元测试如下:
public class ThingUnitTest extends Specification {
def "doing a thing delegates to the context"() {
given : def thing = createThing()
when : thing.doThing()
then : 1 * thing.context.doThing()
}
def createThing() {
def thing = new ThingImpl()
thing.context = createThingContext()
return thing
}
def createThingContext() {
def context = Spy(ThingContext)
context.foo = Mock(Foo)
context.bar = Mock(Bar)
return context
}
}
该测试将顺利运行。但事实证明,我还有其他测试需要 ThingContext
,因此我想将 createThingContext
代码移至公共(public)类中:
public class ThingContextFactory extends Specification {
def createThingContext() {
def context = Spy(ThingContext)
context.foo = Mock(Foo)
context.bar = Mock(Bar)
return context
}
}
然后按如下方式编写我的单元测试:
public class ThingUnitTest extends Specification {
...
def createThingContext() {
return new ThingContextFactory().createThingContext()
}
}
但现在测试失败了,断言 1 * thing.context.doThing()
因零交互而失败。
我还尝试了以下方法:
public class ThingContextFactory {
def createThingContext() {
def mocking = new MockingApi()
def context = mocking.Spy(ThingContext)
context.foo = mocking.Mock(Foo)
context.bar = mocking.Mock(Bar)
return context
}
但现在测试失败,并显示 MockingApi.invalidMockCreation ... InvalidSpec
请注意,我不想在这里使用继承,而是将常见的模拟代码移至辅助类中。但是当我这样做时,我的 spock 测试失败了。
是否有一些适当的方法来重构 Spock 模拟代码?
最佳答案
从 Spock 0.7 开始,模拟对象只能在使用它们的测试类或其父类(super class)中创建。这可能会在下一个版本中发生变化。
关于unit-testing - 将模拟代码重构到另一个类中会导致 Spock 测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22368000/