自定义spock注释来处理应用和清理元类更改?

时间:2014-06-18 04:48:42

标签: groovy annotations spock

当我使用Spock和Groovy运行单元tess时,我想修改类型 Bar 的元类。

目前我执行以下操作:

@ConfineMetaClassChanges(Bar) -- this will cleanup the metaclass changes
class FooSpec extends Specification {

  def setupSpec() {
    BarHelper.setupMetaClass() -- this applies the metaclass changes
  }

  def "test Foo"() {
    given:
      def bar = createBar()
      def foo = createFoo(bar.x, bar.y)
    ...
  }

}

class BarHelper {
  static def setupMetaClass() {
    Bar.metaclass.x = { ... }
    Bar.metaclass.y = { ... }
  }

}

有两个操作来(a)改变元类和(b)清理元类变化是浪费。我想知道我是否可以写一个兼具两者的注释,例如:

@UsingBar -- internally, calls BarHelper.setupMetaClass(), and 
          -- also invokes @ConfineMetaClassChanges(Bar)
class FooSpec extends Specification {

  -- no need for setupSpec() method now

  def "test Foo"() {
    given:
      def bar = createBar()
      def foo = createFoo(bar.x, bar.y)
    ...
  }

}

使用JUNit我可以写一个测试规则或类规则来做类似的事情,但我不确定Spock的最佳实践。

1 个答案:

答案 0 :(得分:0)

我认为我找到了一个更简单的解决方案:使用常规类别和Spock @Uses注释:

class BarCategory {
  static getX(Bar bar) { ... }
  static getY(Bar bar) { ... }
}

@Uses(BarCategory)
public class FooSpec extends Specification {

  def "test Foo"() {
    given:
      def bar = createBar()
      def foo = createFoo(bar.x, bar.y)
      ...
  }

}

这相当于以下内容:

def "test Foo"() {
  given:
    uses(BarCategory) {
      def bar = createBar()
      def foo = createFoo(bar.x, bar.y)
    }
    ...

}

我不需要担心感染其他代码的元类更改。