unit-testing - 将模拟代码重构到另一个类中会导致 Spock 测试失败

标签 unit-testing groovy spock

我的 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/

相关文章:

c# - 如何使用 JustMock 模拟构造函数?

java - android 中 ProgressDialog 的 Robolectric 测试

jenkins - 是否有用于 Replay 的 Jenkins 环境变量?

hibernate - Grails - 非空属性引用空值或 transient 值

unit-testing - Angular 2. 在单元测试中发出悬停事件

python - 在多线程上下文中模拟以在 Python 中进行测试

groovy - 在 ArrayList 上与 groovy 对象相交

testing - 多个测试的相同 `where` 子句

testing - 我可以在没有 Grails 或 Gradle 或其他任何东西的情况下使用 Spock 和 Geb 吗?

groovy - 如何从命令行运行 spock 测试?