使用嵌套的 TestConfiguration 在 Spring Boot 2.1 切片测试中覆盖 bean



我刚刚将一个应用程序从Spring Boot 1.x迁移到2.1。我的一个测试由于更改 bean 覆盖默认值而失败

我试图将spring.main.allow-bean-definition-overriding设置为true但它不起作用。

您可以使用以下类重现此问题:

@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());
}
}

失败的测试。Spring Boot 2.1 从不调用clock()方法,而 Spring Boot 1.5 或 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"));
}
}
}

尝试修改 ContextConfiguration 注释。它应该是:@ContextConfiguration(classes = {MyService.class,ClockConfig.class})。 您明确指定了要在测试中导入的配置@ContextConfiguration注释,因此根本不加载@TestConfiguration。如果您排除@ContextConfiguration它可以工作。由于您删除了MyService的配置,因此您必须在测试配置中提供MyServicebean。试试这个:

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

最新更新