问题描述
我在Quarkus应用程序中有两个类,我们将它们称为服务A和服务B。服务B是A的依赖项。当我测试ServiceA时,我想模拟ServiceB。当我测试ServiceB时,我想测试真实的服务B。
I have two classes in a Quarkus application, let’s call them Service A and Service B. Service B is a dependency of A. When I test ServiceA, I want to mock ServiceB. When I test ServiceB, I want to test the real Service B.
我已经在。如果将其放在/ test目录中,则ServiceATest将正确获取该模拟。但是我的ServiceBTest类也会如此。如何有选择地将模拟注入不同的类?更好的是,我可以针对不同的方法有选择地使用不同的模拟吗?
I've created a MockServiceB class following this guide on quarkus.io. If I put it in my /test directory, my ServiceATest will properly grab the mock. But so will my ServiceBTest class. How can I selectively inject mocks to different classes? Better yet, can I selectively use different mocks for different methods?
(我尝试回退到使用Mockito,但除非我弄错了,否则它似乎不适用于Quarkus& QuarkusTest。)
(I tried falling back to using Mockito, but it doesn't seem to work with Quarkus & QuarkusTest, unless I'm mistaken.)
@ApplicationScoped
public class ServiceA {
@Inject
ServiceB serviceB;
public int giveMeANumber() {
serviceB.getNumber();
}
}
@ApplicationScoped
public class ServiceB {
public int getNumber() {
// does the real work;
return 1;
}
}
@QuarkusTest
class ServiceATest {
@Inject
ServiceA serviceA;
@Test
public void shouldReturnNumber() {
int number = serviceA.giveMeANumber();
assertEquals(1, number);
}
}
@Mock
@ApplicationScoped
class MockServiceB extends ServiceB {
@Override
public int getNumber() {
// don’t do the real work
return 1;
}
}
@QuarkusTest
class ServiceBTest {
@Inject
ServiceB serviceB;
@Test
public void shouldGetNumber() {
int number = serviceB.getNumber();
// uses the mock, I don't want it to
assertEquals(1, number);
}
}
推荐答案
开始在Quarkus 1.4中,您可以对普通范围内的CDI bean使用Mockito模拟(因此可以模拟 @ApplicationScoped
, @Singleton
不能)使用 @InjectMock
注释。
请参见以获取文档和作为示例用法。
Starting with Quarkus 1.4, you can use Mockito mocks for normal scoped CDI beans (so @ApplicationScoped
can be mocked, @Singleton
can't) using the @InjectMock
annotation.See this for documentation and this for an example usage.
这篇关于在某些情况下,如何在QuarkusTest中使用模拟而在其他情况下不使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!