2014-03-13 45 views
1

我有一个Groovy /斯波克单元测试如下:重构嘲笑代码成另一种类导致斯波克测试失败

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 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模拟代码?

回答

1

从Spock 0.7开始,只能在使用它们的测试类或其超类中创建模拟对象。这可能会在下一个版本中改变。

+0

感谢您的澄清。猜猜我需要将通用代码移到基类中(有时这是一件好事,有时候不是)。在未来的版本中放宽此限制+1。 –

+1

我试图在特质中创建模拟,这似乎也不起作用。特质是相同的答案还是可以使其工作? – meyertee