gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:52:31 27 4
gpt4 key购买 nike

我刚刚将一个应用程序从 Spring Boot 1.x 迁移到 2.1。由于 bean overriding default 的更改,我的一项测试失败了

我尝试将 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 的配置,您必须提供MyService bean 在你的测试配置中。试试这个:

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

关于java - 使用嵌套 TestConfiguration 覆盖 Spring Boot 2.1 切片测试中的 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57418014/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com