Noteworthy features of Spock — The finale

In this article we will continue exploring more interesting features that Spock has to offer:

Let’s start with the old method:

Consider a class that implements a buffer:

And the following unit test for it:

As we can see, Spock is able to know what the value of the buffer.text variable was before the action append was called.

Testing exceptions:

You can easily test exceptions using the thrown keyword:

Or if you want to check more information about the exception:

Complex scanarios with @Stepwise

@Stepwise is an annotation that we can use to execute tests that depend on something that needs to have happened before. In general it is a bad idea not to have isolated tests, but I will present this annotation since it can be useful in certain cases.

This is an example of a functional test in which I am exercising an API. I am interested in retrieving a delivery, and in the underlying model, the delivery belongs to a user, so a user must exist first before the delivery. You can either use this technique, or just create a user in the system without exercising the API through the first test. Use this technique wisely.

The @IgnoreIf annotation

You can use this annotation to avoid the execution of a test when a specific condition happens. Let’s see an example:


You can also exclude tests if the Java version is not the one that you require in the project with @IgnoreIf({ javaVersion < 1.8 }) or ignore tests based on system properties or environment variables with @IgnoreIf({ Boolean.valueOf(properties[‘env.staging’]) }), @IgnoreIf({ Boolean.valueOf(env[‘ENV_STAGING’]) }

Property testing

I am going to finally reference a library called Spock Genesis that you can use to write your property tests. Let’s see an example of it:

I hope you enjoyed this overview of Spock and you find interesting the advanced capabilities and features that it offers in comparison to other testing libraries.

Happy testing!

For more information about Spock, visit the Spock Framework Reference Documentation.

This article appeared first on Kenfos Blog

Tags: , ,


Leave a Reply

Your email address will not be published. Required fields are marked *