Test singletons
Throughout the rest of this article, I use JUnit in concert with log4j to test singleton classes. If you are not familiar with JUnit or log4j, see Resources.
Example 2 lists a JUnit test case that tests Example 1's singleton:
Example 2. A singleton test case
import org.apache.log4j.Logger;
import junit.framework.Assert;
import junit.framework.TestCase;
public class SingletonTest extends TestCase {
private ClassicSingleton sone = null, stwo = null;
private static Logger logger = Logger.getRootLogger();
public SingletonTest(String name) {
super(name);
}
public void setUp() {
logger.info("getting singleton...");
sone = ClassicSingleton.getInstance();
logger.info("...got singleton: " + sone);
logger.info("getting singleton...");
stwo = ClassicSingleton.getInstance();
logger.info("...got singleton: " + stwo);
}
public void testUnique() {
logger.info("checking singletons for equality");
Assert.assertEquals(true, sone == stwo);
}
}
Example 2's test case invokes ClassicSingleton.getInstance() twice and stores the returned references in member variables. The testUnique() method checks to see that the references are identical. Example 3 shows that test case output:
Example 3. Test case output
Buildfile: build.XML
init:
[echo] Build 20030414 (14-04-2003 03:08)
compile:
run-test-text:
[Java] .INFO main: getting singleton...
[java] INFO main: created singleton: Singleton@e86f41
[java] INFO main: ...got singleton: Singleton@e86f41
[java] INFO main: getting singleton...
[java] INFO main: ...got singleton: Singleton@e86f41
[java] INFO main: checking singletons for equality
[java] Time: 0.032
[java] OK (1 test)
As the preceding listing illustrates, Example 2's simple test passes with flying colors—the two singleton references oBTained with ClassicSingleton.getInstance() are indeed identical; however, those references were obtained in a single thread. The next section stress-tests our singleton class with multiple threads.
Multithreading considerations