开发者

Is Guice needed in unit test?

I was told the Guice is aim to produce testable code, and not needed in the unit t开发者_StackOverflowest. But how can I test a Singleton(@Singleton) without use Guice?


You don't need Guice (or any DI framework) in unit tests, the SUT is normally small enough that manual DI is fine and good.

Now as to how to "test a singleton". The same way you test any other class, that is part of the beauty of singleton-as-a-scope. In your test methods create a new instance of the "singleton", test it and then throw it away. Remember you don't want the SUT to be affected by previous tests and you will want to be able to set different dependencies for each test so the fact that you're using the scope and not the design pattern is a good thing. You don't need to do anything special to test it.


Actually, my personal take is that any test that requires DI framework can be viewed with suspicion -- it sounds rather more like an integration test, not unit test. Unit tests should be stand-alone, and you SHOULD manually and explicitly wire all dependencies, including mock versions of things you don't want to test. I know that in mainstream dev lingo term "unit test" may be diluted mean any testing written by developers. This does not mean it is proper usage of the term however.

In that light, no, you should have to (and probably just should not!) rely on Guice or Spring DI.

Great thing about Guice (et al) is actually this: by using them for full systems, you make testing without any DI much easier.

So I think the highest rated answer is correct: to test a singleton, just create and test it. There is no specific magic to it.


Guice does dependency injection, and you need it in tests too, I guess.
Guice make it simple to change implementation for injected classes to mock objects (stubs, not real objects). So your tests can run in stub enviroment and be tested faster and independently of other layers of your app.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜