Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Mock/@InjectMocks for groovy - spock

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?

like image 507
zibi Avatar asked Dec 11 '13 19:12

zibi


People also ask

Can we use mock and InjectMocks together?

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.

How do you mock a method in Spock?

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.

Does InjectMocks inject spy?

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.

What does InjectMocks annotation do?

@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.


1 Answers

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.

like image 104
Peter Niederwieser Avatar answered Sep 19 '22 05:09

Peter Niederwieser