views:

418

answers:

3

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

A: 

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.

Nikita Prokopov
+6  A: 

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 effected by previous tests and you will want to be able to set different dependencies for each test so the fact that your using the scope and not the design pattern is a good thing. You don't need to do anything special to test it.

mlk
Thanks for your reply, mlk. I've mixed up unit test with integration test.
eric2323223
Ah. For integration tests I try to use Guice and the live modules for the SUT. After all that is all part of the SUT. You might be interested in Guiceberry if you use JUnit to run your integration tests. http://code.google.com/p/guiceberry/
mlk
What's an "SUT"?
Ladlestein
SUT - System Under Test.
mlk
http://xunitpatterns.com/SUT.html
mlk
+1  A: 

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.

StaxMan