@Mock/@InjectMocks for groovy - spock
Asked Answered
Q

5

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?

Quest answered 11/12, 2013 at 19:56 Comment(0)
V
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.

Voigt answered 11/12, 2013 at 21:31 Comment(1)
Is @InjectMocks available in any third-party Spock extension? I miss this feature in Spock.Wisent
S
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;
}
Stage answered 16/10, 2021 at 3:14 Comment(3)
Tried it but it is not workingHemianopsia
I could be wrong but what about accessing the member of the class under test and assign values directly, as in groovy nothing is privateHemianopsia
I don't think can do with private fields.Poster
S
0

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

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

Shevlo answered 3/12, 2022 at 14:40 Comment(0)
H
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.

Hemianopsia answered 6/1, 2023 at 9:49 Comment(0)
U
0

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: 
    }
}
Umont answered 15/7 at 14:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.