11

I'm having following config in my production files:

@Configuration
internal class Config {

  @Bean
  fun clock() = Clock.systemUTC()
}

In tests:

@Configuration
class ClockTestConfiguration {

  @Bean
  fun clock() = SetableClock()
}

My test annotations:

@SpringBootTest(
  webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
  classes = [
    MyApplication::class,
    ClockTestConfiguration::class
  ]
)
class MyTest {
...

When I was using Spring Boot 2.0.5.RELEASE it worked like a charm. After upgrading to 2.1.0.RELEASE it fails during bean registration.

Caused by: org.springframework.beans.factory.support.BeanDefinitionOverrideException: Invalid bean definition with name 'clock' defined in com.foo.clock.ClockTestConfiguration: 
Cannot register bean definition [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=clockTestConfiguration; factoryMethodName=clock; initMethodName=null; destroyMethodName=(inferred); 
defined in com.foo.clock.ClockTestConfiguration] for bean 'clock': There is already [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=config; factoryMethodName=clock; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/foo/clock/Config.class]] bound.
at org.springframework.beans.factory.support.DefaultListableBeanFactory.registerBeanDefinition(DefaultListableBeanFactory.java:894)

Is there a clean way to override such bean?

pixel
  • 24,905
  • 36
  • 149
  • 251

1 Answers1

20

You could use the properties attribute of @SpringBootTest to set spring.main.allow-bean-definition-overriding=true.

Andy Wilkinson
  • 108,729
  • 24
  • 257
  • 242
  • Great solution. I wonder why this is not set to `true` by default when using `@SpringBootTest`. – andy Mar 19 '21 at 10:23
  • 2
    It isn't enabled by default as that could result in your tests all passing even though your application won't start due to a duplicate bean. – Andy Wilkinson Mar 19 '21 at 10:30