B.6. Spock InjectMocks extension

In a complex unit test in which the class under test is using many other mocks (imagine an EJB class that uses other EJBs), it might be tedious to inject all mocks one by one using the respective setters.

The Spock Collaborators extension (https://github.com/marcingrzejszczak/spock-subjects-collaborators-extension) can be used to automatically inject these dependencies (in a similar manner to Spring automatic injection[1]) by type. Both constructor and setter injection are supported.

1

The Spock extension is inspired by the Mockito @InjectMocks annotation.

Using the extension is as simple as annotating the class under test with @Subject (which is different from the annotation already supported by Spock), and the mocks to be injected with the @Collaborator annotation. After the Spock test runs, you’ll know that all classes marked with the latter annotation will be injected into the class marked with the former. You should have exactly one class marked with @Subject, and one or more classes marked with @Collaborator in each Spock specification.

Here’s the example shown on its web page.

Listing B.4. Automatic injection of mocks

If you want to use this extension, make sure that the @Subject annotation is imported with com.blogspot.toomuchcoding.spock.subjcollabs.Subject instead of the standard spock.lang.Subject that’s used by core Spock for documentation purposes, as described in chapter 4.

The code can be found in Maven central and is therefore easy to use in your own Java project.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.109.234