Skip to content

Override bean in Spring Boot 2.1 slice test with nested TestConfiguration #17830

@sydneyhenrard

Description

@sydneyhenrard

I just migrated an application from Spring Boot 1.x to 2.1. One of my test is failing due to a change to bean overriding default.

I tried to set spring.main.allow-bean-definition-overriding to true but it's not working. I managed to make it work by using a standalone @TestConfiguration class that I import. But if it's nested, it does not work.

You can reproduce the issue with the following classes:

@Configuration
public class ClockConfig {
    @Bean
    public Clock clock() {
        return Clock.systemUTC();
    }
}
@Service
public class MyService {
    private final Clock clock;
    public MyService(Clock clock) {
        this.clock = clock;
    }
    public Instant now() {
        return clock.instant();
    }
}
@RestController
public class MyResource {
    private final MyService myService;
    public MyResource(MyService myService) {
        this.myService = myService;
    }
    @GetMapping
    public ResponseEntity<Instant> now() {
        return ResponseEntity.ok(myService.now());
    }
}

The failing test. The clock() method is never called with Spring Boot 2.1 whereas it was with Spring Boot 1.5 or Spring Boot 2.0.

@RunWith(SpringRunner.class)
@WebMvcTest(MyResource.class)
@ContextConfiguration(classes = MyService.class)
public class ResourceTest {
    @Autowired
    private MockMvc mvc;
    @Test
    public void test() {
    }
    @TestConfiguration
    static class TestConfig {
        @Bean
        public Clock clock() {
            return Clock.fixed(Instant.MIN, ZoneId.of("Z"));
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: declinedA suggestion or change that we don't feel we should currently apply

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions