gpt4 book ai didi

java - Spring Boot 中 ApplicationRunner 的单元测试未获取正确的 bean 定义

转载 作者:太空宇宙 更新时间:2023-11-04 10:35:49 26 4
gpt4 key购买 nike

如何在单元测试中使用@ConditionalOnProperty注解加载配置?

我有以下@Configuration和@Component

@Configuration
@ConditionalOnProperty(value = {"batch"}, havingValue = "Crawler")
public class CrawlerConfiguration
{
@Bean
@Profile("production")
public Crawler crawler(@Value("${name}") String name)
{
return new Crawler(name, true);
}

@Bean
@Profile("test")
public Crawler crawlerTest(@Value("${name}") String name)
{
return new Crawler(name, false);
}

}


@Component
public class Crawler implements ApplicationRunner
{
private String name;
private boolean withScheduler;

public Crawler(String name, boolean withScheduler)
{
this.name = name;
this.withScheduler = withScheduler;
}
@Override
public void run(ApplicationArguments args) throws Exception
{
// do something
}
}

单元测试。

@RunWith(SpringRunner.class)
@SpringBootTest(classes={CrawlerConfiguration.class})
public class CrawlerTest
{
@Autowired
private Crawler crawler;

@Test
public void run() throws Exception
{
crawler.run(new DefaultApplicationArguments(new String[]{}));
}
}

运行此测试会给我这样的警报。

==========================

自动配置报告

正匹配:

否定匹配:

爬虫配置: 不匹配: - @ConditionalOnProperty (batch=Crawler) 未找到属性“batch”(OnPropertyCondition)

排除:

None

无条件类:

None

最佳答案

通过在 @SpringBootTest 添加属性来解决...如下所示。

@SpringBootTest(classes={CrawlerConfiguration.class}, properties = {"batch=Crawler", "name=myName"})

关于java - Spring Boot 中 ApplicationRunner 的单元测试未获取正确的 bean 定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49495692/

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