Spock Framework Documentation
repository·master·Indexed 25 days ago
https://github.com/spockframework/spockA BDD-style testing and specification framework for Java and Groovy. This documentation covers development environment setup for JDK 11 and 17, IDE configuration for IntelliJ IDEA and Eclipse, and detailed guides on data-driven testing using data tables, pipes, and the combined: label. It also details framework extensions such as @Ignore, @Requires, @Stepwise, and @PendingFeature, as well as global configuration via SpockConfig.groovy.
What's inside Spock
- Spock is a BDD-style (Behavior-Driven Development) developer testing and specification framework designed for Java and Groovy applications. It is based on the JUnit Platform and requires Java 8+ and Groovy 2.5+. For projects using Java 12+, Groovy 3.0 or newer is recommended.
Limitations of using Traits with Specifications
masterTraits on Specifications are not officially supported by Spock due to how Groovy implements traits and AST transformations. While some use cases may work, there is no guarantee that AST transformations will run on a trait as they do on a regular class. Use traits in Specifications at your own risk.Set up the Spock development environment
masterSpock is built with Gradle. To develop locally, you must have both JDK 11 and JDK 17 installed. The build process itself runs on JDK 17, but requires JDK 11 to be available via Gradle toolchains.
- Clone the repository.
- Ensure JDK 11 and 17 are installed.
- If Gradle cannot find JDK 11, set the
JDK11environment variable to its location. - Verify toolchains by running
./gradlew javaToolchains. - Run the build using the Gradle Wrapper:
./gradlew build.
Use JUnit 4 features in Spock 2.0
masterSupport for JUnit 4 has been removed from the corespock-coremodule. If your codebase requires JUnit 4 features (such as@Rule), you must include thespock-junit4module. Additionally, you should replace the JUnit 4TemporaryFolderrule with the Spock built-in@TempDirextension.Integrate Guice IoC with Spock
masterTo integrate the Guice IoC container with Spock, add the
spock-guicedependency.With Spock 1.2+, detached mocks are automatically attached to the
Specificationif they are injected using the@Injectannotation.Install the Spock Spring module
masterTo enable integration with the Spring TestContext Framework (including support for
@ContextConfiguration,@ContextHierarchy,@BootstrapWith,@SpringBootTest, and@WebMvcTest), add the following dependency to your project:org.spockframework:spock-springorg.spockframework:spock-springCreate an annotation-driven local extension
masterTo create a local extension driven by annotations, implement the
IAnnotationDrivenExtensioninterface.Requirements for your annotation class:
- Must have
@Retention(RUNTIME). - Must have
@Targetset toFIELD,METHOD, orTYPE(depending on usage). - Must be annotated with
@ExtensionAnnotation(YourExtensionClass.class).
Note on Spock 2.4+: If your extension is thread-safe and does not need to store
Specification-specific state, implementIStatelessAnnotationDrivenExtensioninstead.Repeatable Annotations: Since Spock 2.0, annotations can be
@Repeatable. Use thevisit...Annotations(List<T> annotations, ...)methods to handle multiple instances applied to the same target.- Must have
Inject Method Parameters (Spock 2.4+)
masterSince Spock 2.4, extensions can target method parameters directly.
- Define an annotation with
@Target({ElementType.PARAMETER}). - Implement
IAnnotationDrivenExtension.visitParameterAnnotation(T annotation, ParameterInfo parameter). - Register a custom interceptor or use the built-in
ParameterResolver.Interceptorto handle the injection.
Manual Injection (Pre-2.4 or Advanced): You can manually inject values by modifying
invocation.arguments. For Spock 2.0+, theargumentsarray size matches the method parameter count. If you need to expand it, you must create a new array, copy existing elements, and assign the new array toinvocation.arguments.- Define an annotation with
Run a Spock Example Project locally
masterTo run Spock in your local development environment, use the Spock Example Project. The project includes pre-configured builds for Ant, Gradle, and Maven that require no additional setup. The Gradle build is designed to bootstrap Gradle itself and can be used to set up environments in Eclipse or IntelliJ IDEA with a single command.Fix Class Initialization Order issues (Spock 0.6+)
masterIn Spock 0.6 and later, the initialization order for inherited specifications changed to a more conventional order: field initializers are executed by class level (Base fields, then Derived fields) before any
setup()methods are called.This means you cannot rely on a base class
setup()method to initialize a field that a derived class uses in its field initializer.Broken Pattern:
class Base extends Specification { def base def setup() { base = "base" } } class Derived extends Base { def derived = base + "derived" // base is not yet set }Solutions:
- Use a field initializer for
basein theBaseclass. - Move the assignment of
derivedinto asetup()method in theDerivedclass.
- Use a field initializer for
Use Global Groovy Mocks to replace all instances
masterA global Groovy mock (
GroovyMock(global: true)) automatically replaces all real instances of a specific class type for the duration of the feature method. This is useful for intercepting objects that are not explicitly injected.Cautions:
- Constructor Replacement:
GroovyMock(global: true)replaces constructor calls, which returnnullby default. UseGroovySpy(global: true)if you want to keep real constructors working. - JDK Types: Avoid using global mocks for standard JDK types like
ArrayList. - Declaration Order: The global mock must be declared before any new instances of that type are created in the code under test.
- Parallel Execution: If using parallel execution, global mocks require the spec to be annotated with
@Isolatedor the feature to be annotated with@ResourceLock(org.spockframework.runtime.model.parallel.Resources.META_CLASS_REGISTRY).
- Constructor Replacement:
Enable Parallel Execution in Spock
masterTo enable parallel execution in Spock (available since version 2.0), set therunner.parallel.enabledconfiguration property totruein yourSpockConfig.groovyfile. Parallel execution is based on the JUnit Platform and can reduce overall test execution time.