Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override Spring Bean in integration test with custom bean definition?

I would like to reuse Spring production context configuration, but replace a few beans with another ones. If I would like to override them with a mock, I would use @MockBean, which does exactly what I need (overrides bean), but does not allow me to configure a new bean myselves.

I know there is another way to use @ContextConfiguration but it seems too verbose to me.

Thanks.

like image 810
sinedsem Avatar asked Feb 06 '19 21:02

sinedsem


People also ask

How do you override a Spring bean?

Bean Overriding Spring beans are identified by their names within an ApplicationContext. Thus, bean overriding is a default behavior that happens when we define a bean within an ApplicationContext which has the same name as another bean. It works by simply replacing the former bean in case of a name conflict.

Does Spring allow more than one bean definition in the configuration?

Spring Couldn't autowired,there is more than one bean of `` type. Bookmark this question.


1 Answers

You can use @SpyBean - then bean can be stubbed for specific cases (like in the case of @MockBean), but otherwise real bean will be used.

Also, if you actually need to define custom bean definition for tests, then combination of @Primary / @Profile / @ContextConfiguration can be used for this purpose.

For example:

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test")
@ContextConfiguration(classes = {TestConfig.class, ApplicationConfig.class})
public class ApplicatonTest {
    @Profile("test")
    @Configuration
    static class TestConfig {

        @Bean
        @Primary
        public SomeBean testBeanDefinition() {
            SomeBean testBean = new SomeBean();
            // configure SomeBean for test
            return testBean;
        }
    }
    // tests
}
like image 105
Oleksii Zghurskyi Avatar answered Sep 25 '22 06:09

Oleksii Zghurskyi