【发布时间】:2020-02-06 16:57:02
【问题描述】:
我正在尝试测试一个依赖 bean 工作的类,我想模拟它。该 bean 需要一个字符串值,该值是使用 @ConfigurationProperties 从我的 application.yml 文件中接收的,这可能是问题所在,因为在同一测试类中模拟的其他 bean 工作得很好。正常运行应用程序也可以正常运行,因此该错误似乎与@MockBean 在某种程度上有关。
我有这个配置类,它从application.yml 获取值:
@Data
@ConfigurationProperties("some_api")
public class SomeApiDaoConfig {
private String url;
}
此外,该值在 integrationTest application.yml 文件中设置:
some_api:
url: http://localhost:8082
还有这个创建 bean 的工厂:
@Factory
public class SomeApiDaoFactory {
@Singleton
public SomeApiDao someApiDao(SomeApiDaoConfig someApiDaoConfig) {
return new SomeApiDao(someApiDaoConfig.getUrl());
}
}
测试类基本是:
@MicronautTest(packages = {"<<path to someApiDao>>"})
public class ServiceTest {
@Inject private BlockingStub blockingStub;
@Inject private AnotherDao anotherDao;
@Inject private SomeApiDao someApiDao;
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
}
... (tests)
@MockBean(AnotherDao.class)
AnotherDao anotherDao() {
return mock(AnotherDao.class);
}
@MockBean(SomeApiDao.class)
SomeApiDao someApiDao() {
return mock(SomeApiDao.class);
}
但是,当我运行测试时,它会在尝试初始化 SomeApiDao bean 时弹出此错误:
Failed to inject value for parameter [url] of class: <path to test>.$ServiceTest$SomeApiDao3Definition$Intercepted
Message: No bean of type [java.lang.String] exists. Make sure the bean is not disabled by bean requirements (enable trace logging for 'io.micronaut.context.condition' to check) and if the bean is enabled then ensure the class is declared a bean and annotation processing is enabled (for Java and Kotlin the 'micronaut-inject-java' dependency should be configured as an annotation processor).
Path Taken: new GrpcEmbeddedServer(ApplicationContext applicationContext,ApplicationConfiguration applicationConfiguration,GrpcServerConfiguration grpcServerConfiguration,[ServerBuilder serverBuilder],ApplicationEventPublisher eventPublisher,ComputeInstanceMetadataResolver computeInstanceMetadataResolver,List metadataContributors) --> ServerBuilder.serverBuilder(GrpcServerConfiguration configuration,[List serviceList],List interceptors,List serverTransportFilters) --> new Service([SomeApiDao someApiDao]) --> new $ServiceTest$SomeApiDao3Definition$Intercepted([String url],BeanContext beanContext,Qualifier qualifier,Interceptor[] interceptors)
io.micronaut.context.exceptions.DependencyInjectionException: Failed to inject value for parameter [url] of class: <path to test>.$ServiceTest$SomeApiDao3Definition$Intercepted
【问题讨论】:
标签: java testing integration-testing micronaut