gpt4 book ai didi

quarkus - 在对 Quarkus 应用程序进行单元测试时如何模拟其余客户端?

转载 作者:行者123 更新时间:2023-12-02 10:48:47 27 4
gpt4 key购买 nike

Quarkus getting started unittest描述如何模拟注入(inject)的服务。然而,当尝试将此应用于注入(inject)的休息客户端时,这似乎不起作用。

在我的应用程序中,要注入(inject)的类属性是这样定义的

  @Inject
@RestClient
MyService myService;

在我的测试代码中,我创建了一个如下的模拟服务:

@Alternative()
@Priority(1)
@ApplicationScoped
public class MockMyService extends MyService {

@Override
public MyObject myServicemethos() {
return new MyObject();
}
}

请注意,此服务未注册或注释为 RestClient。像这样运行我的单元测试会出现以下错误:

org.junit.jupiter.api.extension.TestInstantiationException: TestInstanceFactory [io.quarkus.test.junit.QuarkusTestExtension] failed to instantiate test class [...MyMediatorTest]: io.quarkus.builder.BuildException: Build failure: Build failed due to errors
[error]: Build step io.quarkus.arc.deployment.ArcAnnotationProcessor#build threw an exception: javax.enterprise.inject.spi.DeploymentException: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type ...MyService and qualifiers [@RestClient]
- java member: ...MyMediator#myService
- declared on CLASS bean [types=[java.lang.Object, ...MyMediator], qualifiers=[@Default, @Any], target=...MyMediator]

at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.invokeTestInstanceFactory(ClassTestDescriptor.java:314)
...

我也许可以通过添加额外的服务层来克服这个问题。但这感觉就像是走错了方向。

我该如何解决这个问题。

亲切的问候,

米斯尔

最佳答案

我刚刚遇到了同样的问题。文档中似乎有更新以及我遇到的一些极端情况,但谷歌搜索首先将我发送到这里,所以我会为 future 的读者添加我的调查结果。

根据文档,您已经不需要创建模拟类 https://quarkus.io/guides/getting-started-testing#using-injectmock-with-restclient

但是可以像这样使用它

服务等级

@RegisterRestClient(configKey = "country-api")
@ApplicationScoped
public interface MyService

服务使用情况

@Inject
@RestClient
MyService myService;

在测试中模拟它,例如

@InjectMock
@RestClient
MyService myService;

到目前为止一切顺利,但遵循文档 https://quarkus.io/guides/rest-client如果您需要configKey,您可能会以

结束
# Your configuration properties
country-api/mp-rest/url=https://restcountries.eu/rest #
!!country-api/mp-rest/scope=javax.inject.Singleton # /

在你的配置文件中。然后就会遇到这些问题

Ability to use InjectMock on MicroProfile RestClient # 8622

Usage of InjectMock on MicroProfile RestClient # 9630

Error when trying to Test RestClient # 12585

也就是说:如果您将 configKey 与 RegisterRestClient 一起使用,则必须注意不要

country-api/mp-rest/scope=javax.inject.Singleton # 

在配置文件中,该文件优先于 MyService 接口(interface)上的 @ApplicationScoped

关于quarkus - 在对 Quarkus 应用程序进行单元测试时如何模拟其余客户端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56393462/

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