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?
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?
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.
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;
}
https://github.com/marcingrzejszczak/spock-subjects-collaborators-extension
you can use @Collaborator
and @Subject
instead @Mock
and @InjectMocks
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.
Use @SpringBean from org.spockframework.spring https://spockframework.org/spock/docs/2.2-SNAPSHOT/module_spring.html
@ActiveProfiles(['test'])
@Slf4j
@SpringBootTest(classes = MyApplication.class, webEnvironment = RANDOM_PORT)
@TestExecutionListeners(DependencyInjectionTestExecutionListener)
class MyServiceSpec extends Specification {
@Subject
@Inject
MyService service
@SpringBean
AnotherService anotherService = Mock()
def "Test with the injected service"() {
given:
when: "using service"
then:
}
}
© 2022 - 2024 — McMap. All rights reserved.
@InjectMocks
available in any third-party Spock extension? I miss this feature in Spock. – Wisent