0

Is it possible to externalize @MockBean definitions, and combine them with composition instead of inheritance?

Because I find myself often repeating mock definitions, and I would rather be able to load/inject them and define them outside of the test class.

Example:

@SpringBootTest
public class Service1Test {
    @MockBean
    private Service1 service1;
    
    @BeforeEach
    public void mock() {
        when(service1.call()).thenReturn(result1);
    }
}

@SpringBootTest
public class Service2Test {
    @MockBean
    private Service2 service2;
    
    @BeforeEach
    public void mock() {
        when(service2.call()).thenReturn(result2);
    }
}

@SpringBootTest
public class Service3Test {
    @MockBean
    private Service1 service1;
    
    @MockBean
    private Service2 service2;
    
    @BeforeEach
    public void mock() {
        when(service1.call()).thenReturn(result1);
        when(service2.call()).thenReturn(result2);
    }
}

I would like to externalize the mocks somehow, so I could just load them. Pseudocode as follows:

public class MockService1 {
    @MockBean
    private Service1 service1;
    
    @BeforeEach
    public void mock() {
        when(service1.call()).thenReturn(result1);
    }
}

@SpringBootTest
@Import({MockService1.class, MockService2.class})
public class Service3Test {

}
membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • Does this answer your question? [How to create reusable @MockBean definitions in @SpringBootTest?](https://stackoverflow.com/questions/67054014/how-to-create-reusable-mockbean-definitions-in-springboottest) – slauth Jul 29 '21 at 10:39

1 Answers1

0

Yes, you can achieve it by using an external configuration class. For example:

@TestConfiguration
public class TestConfig {

 @Bean
 @Primary
 public Foo foo() {
   return mock(Foo.class); //you can use Mockito or a different approach 
   here
 }

 @Bean
 @Primary
 public Bar bar() {
   return mock(Foo.class); 
 }
}

@Import(TestConfig.class)
public class MyTestClass {
 @Autowire 
 private Foo foo;
 @Autowire
 private Bar bar;  
}
Rauf Aghayev
  • 300
  • 1
  • 12