I have two implementations of a non-critical service that is injected by Guice. The implementations publish results to another system. When I’m running locally there is no way to connect to the other system. I have two classes that implement the publish interface: RealPublisher
and EchoPublisher
. EchoPublisher logs what it was passed and returns success.When I’m testing the application I use EchoPublisher
. I need that to change to RealPublisher
when I deploy.
I can see doing this via an @Provides
method that detects the environment and hands back the right implementation. Or swapping out the entire module when I construct the injector.
My build system is Gradle which doesn’t set any environment variables like Bazel when its used to kick off the app (as far as I know) so I’ll need some other way to even detect the environment. Theres the Guice.Stage
value which might make this easy via the @Provides
method. Of course I’ll have to know when to switch that flag, too.
Is there a good way to handle swapping out implementations without having to remember to do it manually each time?
A straightforward way to do this would be set a system property when testing:
// build.gradle
test {
systemProperty("IS_UNDER_TEST", "true")
}
And then in your app you can check for the presence of this property when making the Guice bindings and bind your test class EchoPublisher
when it is detected.