We can write data driven tests with Spock. We can specify for example a data table or data pipes in a where:
block. If we use a data pipe we can specify a data provider that will return the values that are used on each iteration. If our data provider returns multiple results for each row we can assign them immediately to multiple variables. We must use the syntax [var1, var2, var3] << providerImpl
to assign values to the data variables var1
, var2
and var3
. We know from Groovy the multiple assignment syntax with parenthesis ((var1, var2, var3)
), but with Spock we use square brackets.
In the following sample specification we have a simple feature method. The where:
block shows how we can assign the values from the provider to multiple data variables. Notice we can skip values from the provider by using a _
to ignore the value.
Continue reading →
We can use the @Ignore
and @IgnoreRest
annotation in our Spock specifications to not run the annotated specifications or features. With the @IgnoreIf
annotation we can specify a condition that needs to evaluate to true
to not run the feature or specification. The argument of the annotation is a closure. Inside the closure we can access three extra variables: properties
(Java system properties), env
(environment variables) and javaVersion
.
In the following Spock specification we have a couple of features. Each feature has the @IgnoreIf
annotation with different checks. We can use the extra variables, but we can also invoke our own methods in the closure argument for the annotation:
Continue reading →
Spock's unroll feature is very powerful. The provider data variables can be used in the method description of our specification features with placeholders. For each iteration the placeholders are replaced with correct values. This way we get a nice output where we immediately can see the values that were used to run the code. Placeholders are denoted by a hash sign (#
) followed by the variable name. We can even invoke no-argument methods on the variable values or access properties. For example if we have a String value we could get the upper case value with #variableName.toUpperCase()
. If we want to use more complex expressions we must introduce a new data variable in the where
block. The value of the variable will be determined for each test invocation and we can use the result as a value in the method description.
package com.mrhaki.spock
import spock.lang.*
class SampleSpec extends Specification {
@Unroll
def "check if '#value' is lower case"() {
expect:
value.every { (it as char).isLowerCase() } == result
where:
value || result
'A' || false
'Ab' || false
'aB' || false
'a' || true
'ab' || true
}
}
Continue reading →
Gr8Conf 2014 in Copenhagen has been great.
Three days filled with very informative talks, learning the latest from the Groovy community and mostly meeting all the people involved with the Groovy community, both project leads, members and users.
As always the first day of the conference is a university day with workshops that take 3 hours.
This format is more of a hands-on experience.
The day started with a Getting Groovy workshop to learn Groovy and play around with the language given by myself (Hubert Klein Ikkink).
Notes and the presentation can be found at Github.
The following session we attended was Creating RESTful API's with Grails and Spring Security by Alvaro Sanchez-Mariscal.
After some startup problems, we were running out of time, so he did a live coding session.
Where a rest service was created and login functionality added.
I got some good ideas for our upcoming rest workshop.
The final session of the day was really about playing: Getting Groovy With Lego Mindstorms EV3 by Ryan Vanderwerf.
Ryan gave a small introduction about leJOS as an operating system for the Mindstorm computers, capable of running Java code.
But we can also use Groovy and run the compiled classes on a Mindstorm computer.
It is good to use the @CompileStatic
annotation, because otherwise the application will be to slow to run.
After the introduction Ryan had five Mindstorm sets we could play with.
It was fun to write little code snippets with actions for the Mindstorm 'robot' to execute and then upload them to the Mindstorm computer and see the results.
This was really fun and the Groovy support can be even extended by including builders for instruction.
The project is open source and we can all contribute.
Code from the talk is available at Github.
At the same time the workshop about Unleashing the power of AST transformations by Cédric Champeau started.
The great thing about AST transformations is that you can change the bytecode, so non-groovy languages can use it.
There are multiple phases where you can use your transformation, depending on what you want.
These were some hard exercises.
Homework! The workshop is also available online.
Continue reading →
We can add a resourcebundle property file to our application to support internationalization (i18n). The file contains key-value pairs where the value is a localized value per supported language or locale. In IntelliJ IDEA we can easily see which keys are not yet translated. We open a resourcebundle property file and click on the ResourceBundle
tab at the bottom of the editor. We get a list of all available keys on the left and on the right a text area per supported language with the translated values. If a key is not translated for all supported languages it will be colored in red. We only have to select the keys in red and fill in the values on the right for the given languages.
Continue reading →
We can use the run-script
command to run Groovy scripts within the context of a Grails application. We can pass one or more Groovy scripts as argument to the run-script
command. The Grails environment will be configured and we can access the Spring application context, domain classes, Grails services and more. Basically everything we can do in the Grails console or shell can be saved as a Groovy script and run with the run-script
command.
The following Groovy script shows some stats for a Grails application:
Continue reading →
In a previous blog post we have seen how we can use a BaseScript
AST transformation to set a base script class for running scripts. Since Groovy 2.3 we can apply the @BaseScript
annotation on package
and import
statements. Also we can implement a run
method in our Script
class in which we call an abstract method. The abstract method will actually run the script, so we can execute code before and after the script code runs by implementing logic in the run
method.
In the following sample we create a Script
class CustomScript
. We implement the run
method and add the abstract method runCode
:
Continue reading →
Since Groovy 2.3 we can use the @Sortable
annotation to make a class implement the Comparable
interface. Also new comparator
methods are added. All properties of a class are used to implement the compareTo
method. The order of the properties determines the priority used when sorting. With the annotation parameters includes
and excludes
we can define which properties of the class need to be used to implement the compareTo
method.
In the following class with the name Course
we define three properties title
, beginDate
and maxAttendees
. We also apply the @Sortable
annotation. Notice we cannot use int
as a type, because it doesn't implement the Comparable
interface. The class Integer
does.
Continue reading →
We have seen some features of the @Builder
AST transformation in previous and other blog post. We can use another strategy to let the AST transformation generate a class where the class only has a constructor that accepts a builder class. And with @CompileStatic
we can even make sure that all required properties must have a value set by the builder before the constructor accepts the argument. We use the builderStrategy
annotation parameter and set it to InitializerStrategy
:
import groovy.transform.builder.Builder
import groovy.transform.builder.InitializerStrategy
@Builder(builderStrategy = InitializerStrategy)
class Message {
String from, to, subject, body
}
def message = Message.createInitializer()
.from('mrhaki@mrhaki.com')
.subject('Groovy 2.3 is released')
// Returned object is not Message, but
// internal class Message$MessageInitializer
assert !(message instanceof Message)
// Now we can use the initializer in the
// only constructor of Message.
def messageInstance = new Message(message)
assert messageInstance instanceof Message
assert messageInstance.from == 'mrhaki@mrhaki.com'
assert messageInstance.subject == 'Groovy 2.3 is released'
Continue reading →
In a previous post we learned about the new @Builder
AST transformation introduced in Groovy 2.3. We applied to the annotation to our class files and we got a nice fluent API to set property values. But what if we cannot change the class itself, for example if we want to create a fluent API for classes in an external library. Then we can still use the @Builder
AST transformation but we use a different strategy. We can define the builder strategy via a annotation parameter.
In the following sample we assume the Message
class is from an external library and we cannot or do not want to change the class definition. We create a new Groovy class and set the @Builder
annotation on this new class. We use the annotation parameters builderStrategy
to indicate the generated code is not for the new class, but for the class set with the annotation parameter forClass
.
Continue reading →
Since Groovy 2.3 we can easily create a fluent API for our classes with the @Builder
AST transformation. We can apply the annotation to our classes and the resulting class file will have all the necessary methods to support a fluent API. We can customize how the fluent API is generated with different annotation parameters. In Groovy code we already can use the with
method to have a clean way to set property values or use the named constructor arguments. But if our classes need to be used from Java it is nice to give the Java developers a fluent API for our Groovy classes.
In the following sample we apply the @Builder
annotation to a simple class Message
with some properties. We leave everything to the default settings and then the resulting Message
class file will have a new builder
method that return an internal helper class we can use to set our properties. For each property their is a new method with the name of the property so we can set a value. And finally our class contains a build
that will return a new instance of the Message
class with the correct values for the properties.
Continue reading →
Groovy adds a lot of extra methods to the File
object to work with the contents or find and filter files in a directory. These methods are now also added to the java.nio.file.Path
class since Groovy 2.3.
import java.nio.file.*
final Path newFile = Paths.get('output.txt')
if (Files.exists(newFile)) {
Files.delete(newFile)
}
// Different ways to add content.
newFile.write 'START'
newFile.write System.getProperty('line.separator')
newFile << 'Just a line of text'
newFile.withWriterAppend { writer ->
writer.println()
writer.println 'END'
}
// Read contents.
final Path readFilePath = Paths.get('output.txt')
assert readFilePath.readLines().join(';') == 'START;Just a line of text;END'
assert readFilePath.filterLine { it.contains('text') }.toString().normalize() == 'Just a line of text\n'
// Work with Path objects,
// like with File GDK extensions with
// eachFile, eachDir, eachFileRecursive...
final Path root = Paths.get('.')
def paths = root.eachFileMatch(~/.*\.txt$/) {
assert it.toFile().name == 'output.txt'
}
Continue reading →