13

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?

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
zibi
  • 3,183
  • 3
  • 27
  • 47

4 Answers4

12

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.

Peter Niederwieser
  • 121,412
  • 21
  • 324
  • 259
0

Someone wrote an annotation two months ago: https://github.com/msid256/MockInjector4Spock.

The bean you want to test doesn't need to be instantiated manually. All you need to do is to declare it as a field and annotate it with @InjectMocks.

@Service
class ServiceC {
    @Autowired
    public ServiceC(ServiceA a, ServiceB b) {}
}

class DemoSpec extends Specification {
    @Autowired
    ServiceA serviceA;

    ServiceB serviceB = Mock(ServiceB.class)

    @InjectMocks // from MockInjector4Spock - de.github.spock.ext.annotation.InjectMocks
    ServiceC serviceC;
}
pyb
  • 4,813
  • 2
  • 27
  • 45
0

https://github.com/marcingrzejszczak/spock-subjects-collaborators-extension

you can use @Collaborator and @Subject instead @Mock and @InjectMocks

0

In groovy there is no private scope, so we can modify the members of the class under test directly. So we can assign the member to our mocked value.

suvodipMondal
  • 656
  • 10
  • 27