Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Mock Bean in Spring with Spock

Tags:

spring

spock

I'm being hit with the issue that spock doesn't allow Mocks to be created outside of the specification - How to create Spock mocks outside of a specification class?

This seems to be still outstanding so am asking is that giving that i've got a complex and nested DI graph what is the most efficient way to 'inject' a mock representation deep in the graph?

Ideally, I have one bean definition set for normal deployment and another when running unit tests and it is this definition set being the applicable Mocks

e.g.

@Configuration
@Profile("deployment")
public class MyBeansForDeployment {

   @Bean
   public MyInterface myBean() {
       return new MyConcreateImplmentation();
   } 

}

&&

@Configuration
@Profile("test")
public class MyBeansForUnitTests {

   @Bean
   public MyInterface myBean() {
       return new MyMockImplementation();
   } 

}
like image 592
Mannie Avatar asked Jan 25 '26 05:01

Mannie


1 Answers

Since Spock 1.1, you can create mocks outside of a specification class (detached mocks). One of the options is DetachedMockFactory. Take a look at the documentation or my answer to the question you linked.

like image 159
Piotr Góralczyk Avatar answered Jan 27 '26 00:01

Piotr Góralczyk