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