我正在尝试测试一个依赖于 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
最佳答案
@Data
@ConfigurationProperties("some_api")
public class SomeApiDaoConfig {
private String url;
}
我假设@Data
是Lombok注释,因此它为url
创建一个构造函数参数。 Micronaut 在 1.3 之前不支持将配置键注入(inject)构造函数参数,并且需要使用 ConfigurationInject
关于java - Micronaut Test 模拟 bean 无法注入(inject)值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60100017/