Singletons and Other Global Objects
Set Fake Singleton Example
Here's how we would implement Set Fake Singleton:
public class AppLog {
private static AppLog log; public static AppLog singleInstance() {
if (log == null)
createInstance();
return log;
} public static void setSingleInstance(AppLog newLog) {
log = newLog;
}
}public class SomethingTest {
@Test
public void testWhatever() {
AppLog.setSingleInstance(new FakeAppLog());
// … Any uses of AppLog will really use FakeAppLog.
}
}
With this technique, tests replace the singleton. Thus, just like Alternate Construction,
they run the same risk of replacing the log for everybody.
Take care to put the real singleton back for subsequent tests!
(Reading...)
Formatting Hints:
To format... | use this markup: |
---|---|
source code | {source:lang=java|lineNumbers=false}...{source} (Supported languages: java, cpp, csharp, c, python.) |
bold text | __some text__ |
italicized text | ~~some text~~ |
underlined text | @@some text@@ |
a method or class name | ``myMethod(...)`` |