I want to switch between dependencies in the runtime.
Pseudo code:
//use com.realdependency.ConnectionFactoryImpl;
Class A {
// intergration test
void testWithLiveDomain() {
Connection connection = ConnectionFactory.getInstance().getConnection(domain);
}
}
// use com.mymockeddependency.ConnectionFactoryImpl;
class B {
// unit test
void testWithMockDomain() {
Connection connection = ConnectionFactory.getInstance().getConnection(domain);
}
}
If I have both the dependencies in my POM.xml, my class B is using the real dependency instead of the mocked one. How do I restrict class B to use the mocked dependency
This is the perfect candidate for Dependency Injection. If this is is web-app or you can add additional libs like Spring or any kind of DI container (PicoContainer?) you can leverage them to pick dependencies at runtime.
Try googling "java @Alternative annotation".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.