How do I use mocks in some cases but not others in QuarkusTest?

喜欢而已 提交于 2020-04-18 06:57:07

问题


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.

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?

(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);
    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/57450439/how-do-i-use-mocks-in-some-cases-but-not-others-in-quarkustest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!