Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo

Close

#7 TestProperties decorator class

open
nobody
None
5
2014-07-22
2005-02-17
Mark Hale
No

Here is a TestSetup subclass that makes it easy to pass
objects to a test case in the form of properties. I
wrote it so that I could run a test case for an
interface against its implementation classes. (In this
scenerio, in the javadoc below, MyFirstTestObject and
MySecondTestObject would be implementation classes of
some interface and MyTestCase would test compliance
against that interface). I've used a thread-local
variable in the code to make it thread safe.

import java.util.Iterator;
import java.util.HashMap;
import java.util.Map;
import junit.framework.Test;
import junit.framework.TestResult;
import junitx.extensions.TestSetup;

/**
* A TestSetup which provides additional fixture state
in the form of thread-local properties.
* A TestCase can use these properties in its setUp()
method to customize its fixture.
* <pre>
* public static Test suite() {
* TestSuite suite = new TestSuite();
* Map test1Properties = new HashMap();
* test1Properties.put("test.object", new
MyFirstTestObject());
* suite.addTest(new TestProperties(new
TestSuite(MyTestCase.class), test1Properties));
*
* Map test2Properties = new HashMap();
* test2Properties.put("test.object", new
MySecondTestObject());
* suite.addTest(new TestProperties(new
TestSuite(MyTestCase.class), test2Properties));
* return suite;
* }
*
* protected void setUp() throws Exception {
* Map properties = TestProperties.getProperties();
* Object obj = properties.get("test.object");
* // do fixture setup with obj
* }
* </pre>
* @author Mark Hale
*/
public class TestProperties extends TestSetup {
/** Thread-local properties. */
private static final ThreadLocal PROPERTIES =
new ThreadLocal() {
protected Object initialValue() {
return new HashMap();
}
};
/**
* Returns the properties for this fixture.
*/
public static Map getProperties() {
return (Map) PROPERTIES.get();
}

private final Map properties;
/**
* @param properties the properties to be made
available at <code>setUp()</code> time.
*/
public TestProperties(Test test, Map properties) {
super(test);
this.properties = properties;
}
/**
* Adds <code>this</code> properties to the
fixture properties.
*/
protected void setUp() throws Exception {
getProperties().putAll(properties);
}
/**
* Removes <code>this</code> properties from
the fixture properties.
*/
protected void tearDown() throws Exception {
final Map threadLocalProperties =
getProperties();
for(Iterator iter =
properties.keySet().iterator(); iter.hasNext(); ) {

threadLocalProperties.remove(iter.next());
}
}
}

Discussion