### Derived Class Specification with Setup Method
Source: https://github.com/spockframework/spock/blob/gh-pages/docs/2.4/migration_guide.md
Alternative approach to overcome initialization order issues by moving assignments to a setup method.
```groovy
class Derived extends Base {
def derived
def setup() { derived = base + "derived" }
}
```
--------------------------------
### TempDir Parameter Injection Examples
Source: https://github.com/spockframework/spock/blob/gh-pages/docs/2.4/all_in_one.md
Illustrates parameter injection for @TempDir in setupSpec, setup, and feature methods. The types follow the same rules as for field injection.
```groovy
// Use for parameter injection of a setupSpec method
def setupSpec(@TempDir Path sharedPath) {
assert sharedPath instanceof Path
}
// Use for parameter injection of a setup method
def setup(@TempDir Path setupPath) {
assert setupPath instanceof Path
}
// Use for parameter injection of a feature
def demo(@TempDir Path path5) {
expect:
path1 instanceof Path
path2 instanceof File
path3 instanceof Path
path4 instanceof FileSystemFixture
path5 instanceof Path
}
```
--------------------------------
### Example Snapshot Configuration
Source: https://github.com/spockframework/spock/blob/gh-pages/docs/2.4/extensions.md
Provides an example configuration block for Spock snapshots, setting the root directory, update behavior, and handling of mismatches.
```groovy
snapshots {
rootPath = Paths.get("src/test/resources")
updateSnapshots = System.getenv("UPDATE_SNAPSHOTS") == "true"
writeActualSnapshotOnMismatch = !System.getenv("CI")
defaultExtension = 'snap.groovy'
}
```
--------------------------------
### @Retry with Setup, Feature, and Cleanup
Source: https://github.com/spockframework/spock/blob/gh-pages/docs/2.4/extensions.md
Illustrates using @Retry with the SETUP_FEATURE_CLEANUP mode to retry setup and cleanup phases along with the feature method.
```groovy
class FlakyIntegrationSpec extends Specification {
@Retry(mode = Retry.Mode.SETUP_FEATURE_CLEANUP)
def "retry with setup and cleanup"() {
expect: true
where:
data << sql.execute('')
}
}
```
--------------------------------
### TempDir Field Injection Examples
Source: https://github.com/spockframework/spock/blob/gh-pages/docs/2.4/all_in_one.md
Demonstrates field injection for @TempDir with different types and sharing behaviors. Use @Shared for shared directories across features, otherwise each feature gets its own.
```groovy
// all features will share the same temp directory path1
@TempDir
@Shared
Path path1
// all features and iterations will have their own path2
@TempDir
File path2
// will be injected using java.nio.file.Path
@TempDir
def path3
// use a custom class that accepts java.nio.file.Path as sole constructor parameter
@TempDir
FileSystemFixture path4
```
--------------------------------
### Selecting a Mock Maker with Byte Buddy
Source: https://github.com/spockframework/spock/blob/gh-pages/docs/2.4/interaction_based_testing.md
Specify the mock maker to be used for a mocked object. This example uses the 'byte-buddy' mock maker.
```groovy
def subscriber = Mock(mockMaker: MockMakers.byteBuddy, Subscriber)
```
--------------------------------
### Example Gradle Configuration for Snapshot Testing
Source: https://github.com/spockframework/spock/blob/gh-pages/docs/2.4/extensions.md
Demonstrates how to configure snapshot testing within a Gradle build, including setting system properties for the snapshot root path and enabling snapshot updates via a project property.
```groovy
tasks.named("test", Test) {
useJUnitPlatform()
// set the snapshot directory, as resources are already an input we don't need to track them separately
systemProperty("spock.snapshots.rootPath", "src/test/resources")
// allow updating the snapshots with running `gradlew test -PupdateSnapshots`
if (project.hasProperty("updateSnapshots")) {
systemProperty("spock.snapshots.updateSnapshots", "true")
// not strictly necessary but speeds up the process by only executing snapshot tests
useJUnitPlatform {
includeTags("snapshot")
}
}
}
```
--------------------------------
### Detached Mock Factory Setup
Source: https://github.com/spockframework/spock/blob/gh-pages/docs/2.4/interaction_based_testing.md
Initialize a detached mock factory and mock util outside of specifications for reuse across multiple features.
```groovy
@Shared
def mockFactory = new DetachedMockFactory()
@Shared
def mockUtil = new MockUtil()
```
--------------------------------
### Adding All Possible Interceptors
Source: https://github.com/spockframework/spock/blob/gh-pages/docs/2.4/extensions.md
This example demonstrates how to register interceptors at all possible interception points within a Spock specification. Use this as a reference for available points, but typically only a subset is needed.
```groovy
// DISCLAIMER: The following shows all possible injection points that you could use
// depending on need and situation. You should normally not need to
// register a listener to all these places.
//
// Also, when building an annotation driven local extension, you should
// consider where you want the effects to be present, for example only
// for the features in the same class (specInfo.features), or for features
// in the same and superclasses (specInfo.allFeatures), or also for
// features in subclasses (specInfo.bottomSpec.allFeatures), and so on.
// on SpecInfo
specInfo.specsBottomToTop*.addSharedInitializerInterceptor new I('shared initializer')
specInfo.allSharedInitializerMethods*.addInterceptor new I('shared initializer method')
specInfo.addInterceptor new I('specification')
specInfo.specsBottomToTop*.addSetupSpecInterceptor new I('setup spec')
specInfo.allSetupSpecMethods*.addInterceptor new I('setup spec method')
specInfo.allFeatures*.addInterceptor new I('feature')
specInfo.specsBottomToTop*.addInitializerInterceptor new I('initializer')
specInfo.allInitializerMethods*.addInterceptor new I('initializer method')
specInfo.allFeatures*.addIterationInterceptor new I('iteration')
specInfo.specsBottomToTop*.addSetupInterceptor new I('setup')
specInfo.allSetupMethods*.addInterceptor new I('setup method')
specInfo.allFeatures*.featureMethod*.addInterceptor new I('feature method')
specInfo.specsBottomToTop*.addCleanupInterceptor new I('cleanup')
specInfo.allCleanupMethods*.addInterceptor new I('cleanup method')
```
--------------------------------
### Alternative Cross-Multiplication with 'combined:'
Source: https://github.com/spockframework/spock/blob/gh-pages/docs/2.4/data_driven_testing.md
Achieves the same result as the previous example by using a data pipe for one provider and a direct assignment for another, combined with 'combined:'. This demonstrates flexibility in combining different data provider types.
```groovy
where:
a << [1, 2]
combined:
b | c
3 | 5
4 | 6
d = 1
e = a + b
```
--------------------------------
### Example Classes for Detached Mocks
Source: https://github.com/spockframework/spock/blob/gh-pages/docs/2.4/interaction_based_testing.md
Define simple classes 'Engine' and 'Car' to demonstrate the usage of detached mocks.
```groovy
class Engine {
private boolean started
boolean isStarted() { return started }
void start() { started = true }
void stop() { started = false }
}
class Car {
private Engine engine
void drive() { engine.start() }
void park() { engine.stop() }
}
```
--------------------------------
### Usage Example for Custom Mock Maker
Source: https://github.com/spockframework/spock/blob/gh-pages/docs/2.4/extensions.md
Demonstrates how to use the custom FancyMockMaker in a Spock test. It shows how to configure the mock maker with specific settings like fancy types and serialization, and asserts that a specific exception is thrown when the mock is not supported.
```groovy
when:
Mock(ArrayList, mockMaker: FancyMockMakers.fancyMock {
fancyTypes(List.class, String.class)
withSerialization()
})
then:
CannotCreateMockException ex = thrown()
ex.message == "Cannot create mock for class java.util.ArrayList. fancy: Mock with serialization and fancy types is not supported."
```
--------------------------------
### Configure Mockito Mock Settings
Source: https://github.com/spockframework/spock/blob/gh-pages/docs/2.4/extensions.md
Configure created mock objects using Mockito's MockSettings interface during construction. This example shows how to make a mock serializable.
```groovy
Subscriber subscriber = Mock(mockMaker: MockMakers.mockito {
serializable()
})
```
--------------------------------
### Create Directory Tree with FileSystemFixture
Source: https://github.com/spockframework/spock/blob/gh-pages/docs/2.4/utilities.md
Demonstrates how to create a directory structure and files using the FileSystemFixture. Ensure groovy-nio is added as a dependency for enhanced Path methods.
```groovy
import spock.lang.util.FileSystemFixture
import java.nio.file.Files
@TempDir
FileSystemFixture fsFixture
def "FileSystemFixture can create a directory structure"() {
when:
fsFixture.create {
dir('src') {
dir('main') {
dir('groovy') {
file('HelloWorld.java') << 'println "Hello World"'
}
}
dir('test/resources') {
file('META-INF/MANIFEST.MF') << 'bogus entry'
copyFromClasspath('/org/spockframework/smoke/extension/SampleFile.txt')
}
}
}
then:
Files.isDirectory(fsFixture.resolve('src/main/groovy'))
Files.isDirectory(fsFixture.resolve('src/test/resources/META-INF'))
fsFixture.resolve('src/main/groovy/HelloWorld.java').text == 'println "Hello World"'
fsFixture.resolve('src/test/resources/META-INF/MANIFEST.MF').text == 'bogus entry'
fsFixture.resolve('src/test/resources/SampleFile.txt').text == 'HelloWorld\n'
}
```
--------------------------------
### Ant Script Selector Example
Source: https://github.com/spockframework/spock/blob/gh-pages/docs/2.4/all_in_one.md
When using Spock with Ant, replace the removed SpecClassFileSelector with a script selector that forwards to SpecClassFileFinder. This example shows how to configure the script selector in Ant.
```xml
```
--------------------------------
### Customizing Temporary Directory Base Path and Behavior
Source: https://github.com/spockframework/spock/blob/gh-pages/docs/2.4/extensions.md
Illustrates how to configure the base directory, keep behavior, and default cleanup mode for temporary directories using the Spock configuration file.
```groovy
tempdir {
// java.nio.Path object, default null,
// which means system property "java.io.tmpdir"
baseDir Paths.get("/tmp")
// boolean, default is system property "spock.tempDir.keep"
keep true
// spock.lang.TempDir.CleanupMode, default ALWAYS
// allows to set the default cleanup mode to use
cleanup spock.lang.TempDir.CleanupMode.ON_SUCCESS
}
```
--------------------------------
### Implicit Condition in Expect Block
Source: https://github.com/spockframework/spock/blob/gh-pages/docs/2.4/spock_primer.md
Conditions are implicitly handled in 'expect' blocks. This example shows a condition within an 'each' loop.
```groovy
expect:
aList.each { assert it > 0 }
```
--------------------------------
### Feature-Scoped Method Interceptors
Source: https://github.com/spockframework/spock/blob/gh-pages/docs/2.4/all_in_one.md
Add feature-scoped interceptors to specific spec methods like initializers, setups, and cleanups. These are applied per feature.
```groovy
featureInfo.parent.allInitializerMethods.each { method ->
featureInfo.addScopedMethodInterceptor(method, new I('feature scoped initializer method'))
}
featureInfo.parent.allSetupMethods.each { method ->
featureInfo.addScopedMethodInterceptor(method, new I('feature scoped setup method'))
}
featureInfo.parent.allCleanupMethods.each { method ->
featureInfo.addScopedMethodInterceptor(method, new I('feature scoped cleanup method'))
}
```
--------------------------------
### Configuring Temporary Directory Cleanup Behavior
Source: https://github.com/spockframework/spock/blob/gh-pages/docs/2.4/extensions.md
Shows how to configure the cleanup behavior for temporary directories using @TempDir(cleanup = ). Modes include DEFAULT, ALWAYS, NEVER, and ON_SUCCESS.
```groovy
// Example of cleanup modes (not directly executable code, but illustrative)
// @TempDir(cleanup = spock.lang.TempDir.CleanupMode.ALWAYS)
// @TempDir(cleanup = spock.lang.TempDir.CleanupMode.NEVER)
// @TempDir(cleanup = spock.lang.TempDir.CleanupMode.ON_SUCCESS)
```
--------------------------------
### Example Specifications for Exception Counting
Source: https://github.com/spockframework/spock/blob/gh-pages/docs/2.4/extensions.md
These specifications include tests that intentionally fail, either by asserting false or by throwing exceptions, to demonstrate the functionality of the ExceptionCounterGlobalExtension.
```groovy
class ASpec extends Specification {
def "a failing test"() {
expect: false
}
def "a test failing with an exception"() {
given:
if(1==1) throw new IllegalStateException()
expect: true
}
}
class BSpec extends Specification {
def "illegal parameter for List"() {
given:
def value = new ArrayList<>(-1)
expect:
value.empty
}
def "illegal parameter for Map"() {
given:
def value = new HashMap(-1)
expect:
value.empty
}
}
```
--------------------------------
### Example Static Class
Source: https://github.com/spockframework/spock/blob/gh-pages/docs/2.4/interaction_based_testing.md
A private static inner class used to demonstrate mocking of static methods. It contains two static methods: 'staticMethod' and 'otherStaticMethod'.
```groovy
private static class StaticClass {
static String staticMethod() {
return "RealValue"
}
static String otherStaticMethod() {
return "OtherValue"
}
}
```
--------------------------------
### Argument Constraints: Wildcards
Source: https://github.com/spockframework/spock/blob/gh-pages/docs/2.4/all_in_one.md
Illustrates the use of wildcard constraints to match any single argument or any argument list.
```groovy
1 * subscriber.receive() // the empty argument list (would never match in our example)
1 * subscriber.receive(_) // any single argument (including null)
1 * subscriber.receive(*_) // any argument list (including the empty argument list)
```
--------------------------------
### Add Feature-Scoped Method Interceptors
Source: https://github.com/spockframework/spock/blob/gh-pages/docs/2.4/extensions.md
Intercept specific initializer, setup, or cleanup methods within a feature's scope. This allows targeted interception of method executions.
```groovy
featureInfo.parent.allInitializerMethods.each {
featureInfo.addScopedMethodInterceptor(it, new I('feature scoped initializer method'))
}
featureInfo.parent.allSetupMethods.each {
featureInfo.addScopedMethodInterceptor(it, new I('feature scoped setup method'))
}
featureInfo.parent.allCleanupMethods.each {
featureInfo.addScopedMethodInterceptor(it, new I('feature scoped cleanup method'))
}
```
--------------------------------
### Selecting Mock Maker during Mock Creation
Source: https://github.com/spockframework/spock/blob/gh-pages/docs/2.4/release_notes.md
Demonstrates how to select a specific mock maker when creating a mock. This allows for external libraries to contribute mocking logic.
```groovy
Mock(mockMaker:MockMakers.byteBuddy)
```
--------------------------------
### Using Real Constructors with Global Mocks
Source: https://github.com/spockframework/spock/blob/gh-pages/docs/2.4/interaction_based_testing.md
Shows how to configure a global mock to allow real constructors to be called using callRealMethod(). This ensures instances are created as expected.
```groovy
GroovyMock(global: true, RealSubscriber) {
//Allow that the real constructor is called
new RealSubscriber(*_) >> { callRealMethod() }
}
def sub = new RealSubscriber()
sub instanceof RealSubscriber
```
--------------------------------
### Add Feature-Scoped Interceptors (Spock 2.4+)
Source: https://github.com/spockframework/spock/blob/gh-pages/docs/2.4/extensions.md
Utilize feature-scoped interceptors for finer control over initializer, setup, and cleanup stages within a single feature. These execute before spec-level interceptors.
```groovy
featureInfo.addInitializerInterceptor new I('feature scoped initializer')
featureInfo.addSetupInterceptor new I('feature scoped setup')
featureInfo.addCleanupInterceptor new I('feature scoped cleanup')
```