![](/img/trans.png)
[英]How to fix org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'name'?
[英]How to fix a test failing on org.springframework.beans.factory.UnsatisfiedDependencyException Error creating bean with name
我有一个正常工作的Spring Boot应用程序。 在Spring Boot应用程序类中,我有以下两个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时出错。
我的测试clss看起来像这样:
@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的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所需的所有属性?)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.