groovy - 如何在 Spock 中为测试套件设置和清理资源

标签 groovy junit spock

我的 JUnit 套件中有这段代码:

@RunWith(Suite.class)
@Suite.SuiteClasses({ MyJavaTest.class, MyAnotherJavaTest.class })
public class MyIntegrationSuite {
    @BeforeClass
    public static void beforeTests() throws Exception {
        Container.start();
    }

    @AfterClass
    public static void afterTests() throws Exception {
        Container.stop();
    }
}

我想将它重写为 Spock,但我找不到任何方法来进行全局设置,只有 setupSpec()setup() 不是足够了,因为我有多个规范并且我只想启动一个容器。

我试着让套件保持原样并将 Spock 规范传递给它,但是 spock 测试被完全跳过(当我添加 extends Specifications 时)。这可能是因为 Specification@RunWith(Sputnik) 并且它不与 @RunWith(Suite) 一起玩,但我不是确定如何解决这个问题。

是否有任何方法可以使用 Spock 进行全局设置或从 JUnit 套件执行 Spock 规范?

我的 pom.xml( stub 在那里,因为我混合了 java 和 groovy 代码):

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>build-helper-maven-plugin</artifactId>
  <version>${buildhelper.plugin.version}</version>
  <executions>
    <execution>
      <id>add-groovy-test-source</id>
      <phase>test</phase>
      <goals>
        <goal>add-test-source</goal>
      </goals>
      <configuration>
        <sources>
          <source>${basedir}/src/test/groovy</source>
        </sources>
      </configuration>
    </execution>
  </executions>
</plugin>
<plugin>
  <groupId>org.codehaus.gmavenplus</groupId>
  <artifactId>gmavenplus-plugin</artifactId>
  <version>${gmavenplus.plugin.version}</version>
  <executions>
    <execution>
      <goals>
        <goal>generateTestStubs</goal>
        <goal>compileTests</goal>
        <goal>removeTestStubs</goal>
      </goals>
    </execution>
  </executions>
</plugin>

最佳答案

总的来说,Spock 毕竟是一个 JUnit(这就是为什么 surefire 插件可以毫不费力地运行它的原因),所以套件的所有方法都应该有效,尽管我没有使用过这个功能。

此外,如果您有“大量”共享资源,那么您可以尝试以下方法:

abstract class SharedResourceSupport extends Specification {
   def static sharedSource = new SharedSource()
}


class SharedSource {
    public SharedSource() {
        println "Created shared source. Its our heavy resource!"
    }
}


class SpockTest1 extends SharedResourceSupport {
    def "sample test" () {
      expect:
        sharedSource != null
    }
}

class SpockTest2 extends SharedResourceSupport {
    def "another test" () {
      expect:
        sharedSource != null
    }
}

请注意,共享资源是用“静态”定义的,因此它只会在第一个测试访问它时创建一次。

作为处理此问题的不同策略:如果您的测试已经从另一个类继承,您可能需要考虑特征,或者将共享资源公开为单例,以便它保证只存在一个实例。

尝试运行这两个测试,您会看到“Created shared source...”这一行只被调用了一次

关于groovy - 如何在 Spock 中为测试套件设置和清理资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50334904/

相关文章:

xslt - 如何在 xslt 中设置标志/变量以再次输入(与转换为 Junit 格式有关)

java - 如何在 groovy spock 测试中返回模拟列表

java - 如何在 spock 或 hamcrest 中创建自定义域特定断言/匹配器

unit-testing - 使用 Spock 和 Grails 在全局 stub 类中注入(inject) stub 协作者

json - 使用gson Grails View 序列化Map <FooCategory,List <Foo >>

java - 斯波克框架 : matching wildcard arguments

grails - 按值而不是按引用将对象属性复制到映射

java - 从 Java 运行的 Groovy 脚本是否具有相同的类路径?

java - 以非静态方式创建 JUnit TestSuite

java - BlockingQueue 接口(interface)的 JUnit 测试