java - 如何修复 org.springframework.beans.factory.UnsatisfiedDependencyException 错误创建具有名称的 bean 的测试失败
问题描述
我有一个正常工作的 Spring Boot 应用程序。在 Spring Boot 应用程序类中,我有这 2 个 bean:
@Bean
public StatsdMeterRegistry graphiteRegistry(StatsdConfig statsdConfig) {
statsdMeterRegistry = StatsdMeterRegistry
.builder(statsdConfig)
.nameMapper(new GraphiteHierarchicalNameMapper(HOST_TAG))
.build();
return statsdMeterRegistry;
}
@Bean
MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() {
InetAddress localHost;
try {
localHost = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
log.error("Failed to get the host name");
return null;
}
return registry -> registry.config()
.commonTags(HOST_TAG, localHost.getHostName() + "_" + SERVICE_NAME);
}
这些 bean 在运行时工作正常,但在测试时失败:
原因:org.springframework.beans.factory.UnsatisfiedDependencyException:在测试期间创建名为“graphiteRegistry”的bean时出错。
我的测试类看起来像这样:
@RunWith(SpringRunner.class)
@WebMvcTest(IntentModelingController.class)
@TestPropertySource("classpath:application-test.yml")
public class IntentModelingControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private IntentModelingService intentModelingService;
@Autowired
private WebApplicationContext webApplicationContext;
private Gson gson = new Gson();
关于如何在测试期间使这些 bean 可见的任何建议?
编辑:如果我评论第一个 bean 并让第二个 bean 保持原样 - 测试运行良好。
编辑#2:导致问题的第一个 bean 和很好的第二个 bean 之间的区别在于第一个 bean 需要一个参数:yyy.xxx.intentmodeling.server.IntentModelingApplication 中的方法石墨注册表的参数 0 需要一个类型的 bean 'io.micrometer.statsd.StatsdConfig' 找不到。
通过在测试中添加 2 个字段来解决:
@MockBean
private StatsdMeterRegistry statsdMeterRegistry;
@MockBean
StatsdConfig statsdConfig;
解决方案
尝试在测试类之上导入定义 bean 的配置类。
@RunWith(SpringRunner.class)
@WebMvcTest(IntentModelingController.class)
@TestPropertySource("classpath:application-test.yml")
@Import(YourConfig.class)
另一个可能的问题@Bean
是检测到 ,但该graphiteRegistry
方法引发异常。例如,由于缺少属性(我看到您定义了一个 application-test.yml,它是否包含实例化 bean 所需的所有属性?),这可能会发生。