Currently I have 1 Guice module in my project which defines all bindings.
Now I want to write integration tests and I need to bind the dependencies of a specific class. If I use the existing module, Guice will bind all dependencies. But I think this in not correct for integration tests.
So, do I need a module for every class that only the necessary dependencies will be bind?
Thanks.
Creating one Guice module to bind all bindings in a project isn’t optimal, but neither is creating one module per binding.
In general, you simply want to “group related bindings into a module”. Doing so is somewhat of an art, rather than a science, so I can’t give perfect advice.
If your project has a solid Java package structure, then creating one Guice module per package is a good place to start (though, if your packages contain lots of classes, you may even want several per package). Using per-package Guice modules also gives you the advantage of letting you make your implementation classes be package-private (which is good for encapsulation!).
One specific example: if your project has external dependencies, it’s probably good to bind them separately from your application code. For example, if you have a webserver that talks to an RPC service on another server, it’s good to bind the service separately from the code that talks to the service (that way, you can mock out the external service without mocking any application code).
As a crutch, you can also use
Modules.override(...)[1], but doing so is generally a sign that your modules are too big.