How to mock bean in springboot groovy and spock tests?

190 Views Asked by At

This is a spock test using groovy

This is my code

@SpringBootTest
class SrMetricServiceAspectTest extends Specification {
@Autowired
@Qualifier("potentialSrCreation")
private SrCreationService service

@MockBean
SrMetricService srMetricService

@TestConfiguration
static class TestConfig {

    @Bean("potentialSrCreation")
    SrCreationService getSrCreationService() {
        // Return an instance of PotentialSrCreation with necessary dependencies
        return new PotentialSrCreation()
    }
}
}

I have a groovy test in the structure of

def "..." () {
   given: 
      ...
   when:
      ...
   then:
      ...

However when I run the test, service itself is null. Is there an issue with my configuration/injection? I'm trying to define the bean within the test file.

1

There are 1 best solutions below

0
Ryuzaki L On

In the groovy with spock tests you should use @SpringBean to create and inject mocks into application context

@SpringBootTest
class SrMetricServiceAspectTest extends Specification {

@Autowired
@Qualifier("potentialSrCreation")
private SrCreationService service

@SpringBean
SrMetricService srMetricService

   //write tests

}

Using @SpringBean

Registers mock/stub/spy as a spring bean in the test context.

To use @SpringBean you have to use a strongly typed field def or Object won’t work. You also need to directly assign the Mock/Stub/Spy to the field using the standard Spock syntax. You can even use the initializer blocks to define common behavior, however they are only picked up once they are attached to the Specification.

@SpringBean definitions can replace existing Beans in your ApplicationContext.