I recently stumbled upon this interesting concept that may save me much testing efforts.
What I do not understand is how can the provider be injected in runtime?
The scenario is trivial: I am constructing a mock object at run-time with my mocking framework of choice, but I do not know the name of the generated class in advance because it is a mock (so I can’t configure it in advance, not do I want to).
Did anybody make successful use of this technique in unit tests?
Thank you.
The concept described in that article is an Ambient Context that uses a Service Locator in the background.
Because of the use of a static property and the use of the Service Locator, this pattern is very inconvenient for unit testing. To be able to run a test that verifies code that uses this singleton, you need to set up a valid Service Locator and configure it with the singleton (probably a mock instance) that you care about using testing.
Even the example given by the article already suffers from these problems, since the “Do you like singletons?” code, is hard to test:
A better alternative is to use constructor injection to inject that singleton (please excuse my French, but I’m not a native Java speaker):
There was another ‘hidden’ dependency in that code:
System.err.println. It got abstracted using aMessageDisplayerinterface. This code has a few clear advantages:Your tests might look like this:
Your test code will never be as intend revealing as the code above when you’re using the ‘injectable singleton’ pattern as shown in the article.