Spock 1.2 Annotations for Spring Integration Testing

@SpringBean, @SpringSpy, and @UnwrapAopProxy are new annotations in Spock 1.2 that make it easier to inject mocks into the Spring context when doing Integration testing. These can greatly simplify your code from using a @TestConfiguration approach, though there are some drawbacks too. If you’re not familiar with the Spock 1.1 @TestConfiguration method, take a look at the original Spock Spring Integration blog post from Derek Eskens.

@SpringBean

Let’s start with the easiest new annotation @SpringBean. This annotation will tell Spock to add the mocked bean into the Spring test context. To use it you will need to explicitly create the Mock() and include a defined type (instead of using `def`)

@SpringSpy

Similarly, @SpringSpy will wrap a Spy around the bean that Spring creates and puts into the context. For most cases it is simple to just use @SpringSpy in place of @SpringBean.

It becomes more complicated when trying to Spy a Spring AOP Proxied bean. @Validated services are one type of proxied object, as Spring wraps the class to perform the validation.

Without unwrapping the AOP proxy, the error you see in Spock will be very puzzling:

@UnwrapAopProxy

@UnwrapAopProxy is a new Spock 1.2 annotation for easily unwrapping the proxy to use the spied object.

While @SpringBean and @SpringSpy make it very easy to Integration Test, the one drawback is that Spring will create a new test context for each test and will not try to cache and reuse the context between tests. So for very large applications with many tests this can be quite slow. In those cases you will still need to resort to using a reusable @TestConfiguration class.

Manual AOP Proxy unwrapping

In those cases, you will need to manually unwrap the AOP proxy for spying. This can be done using AopTestUtils.getUltimateTargetObject() from the spring-test package:

Spock 1.2-SNAPSHOT

As of this blog post writing in May 2018, Spock 1.2 is still a SNAPSHOT and has not been fully released yet. So to pull in the snapshot you’ll need to use the snapshot repo in your gradle (or maven) file

Hopefully this was a helpful intro to the new annotations available in Spock 1.2. You can try them out in a full source repo with tests by cloning the github repo https://github.com/jeffsheets/spring-spock-integration-testing/tree/feat/mockSpringCglibProxyValidated.

Leave a Reply

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

*

*