开发者

Do I need a Guice module for every class to write integration tests?

Currently I have 1 Guice module in my project which defines all bindi开发者_运维百科ngs. 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.

  1. http://google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/util/Modules.html


Yes, you can have more than one module, and usually you want a different one for your tests. If you didn't use field injection and it's not too much work, you could have your setup build the classes with constructors that are passed the tested objects, including mocks.

Alternatively, and more commonly, remember that your modules' configure methods can install other modules, so if you compartmentalize the stuff that's common between regular operation and integration testing into one module, the remaining two different modules can each install the common one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜