In JUnit / Mockito we have 2 extremly useful annotations: @Mock and @InjectMocks.
In my new project i started using groovy with spock for testing, I'm wondering if there is a replacement for mentioned annotations?
Mockito @InjectMocks annotations allow us to inject mocked dependencies in the annotated class mocked object. This is useful when we have external dependencies in the class we want to mock. We can specify the mock objects to be injected using @Mock or @Spy annotations.
In Spock, a Mock may behave the same as a Stub. So we can say to mocked objects that, for a given method call, it should return the given data. So generally, this line says: itemProvider. getItems will be called once with ['item-'id'] argument and return given array.
Again, note that @InjectMocks will only inject mocks/spies created using the @Spy or @Mock annotation. MockitoAnnotations. initMocks(this) method has to be called to initialize annotated objects. In above example, initMocks() is called in @Before (JUnit4) method of test's base class.
@InjectMocks is the Mockito Annotation. It allows you to mark a field on which an injection is to be performed. Injection allows you to, Enable shorthand mock and spy injections.
There is no real need for @Mock
in Spock, because there is already = Mock()
, which can be used everywhere an annotation can be used (and also in other places). There is an open pull request for @InjectMocks
, but it hasn't been decided if such a feature will make it into spock-core or spock-guice. (Shipping this feature with spock-guice, or at least requiring Guice on the class path, would allow to delegate injection to Guice, rather than reinventing the wheel.) If not, @InjectMocks
could always be shipped as a third-party Spock extension.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With