Simply Singleton -- part2 By David Geary

王朝other·作者佚名  2008-05-31
窄屏简体版  字體: |||超大  

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

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航