01: package abbot.util;
02:
03: import abbot.DynamicLoadingConstants;
04: import junit.extensions.abbot.TestHelper;
05: import junit.framework.TestCase;
06:
07: public class NonDelegatingClassLoaderTest extends TestCase implements
08: DynamicLoadingConstants {
09:
10: public void testNoDelegation() throws Throwable {
11: // Use a shared parent class loader that has the given class in its
12: // path to ensure that the nondelegating loader loads the class and
13: // not its parent.
14: PathClassLoader pcl = new PathClassLoader(DYNAMIC_CLASSPATH,
15: getClass().getClassLoader());
16: String className = DYNAMIC_CLASSNAME;
17: ClassLoader cl = new NonDelegatingClassLoader(
18: DYNAMIC_CLASSPATH, pcl);
19: Class cls = Class.forName(className, true, cl);
20: assertTrue(
21: "Class loader should define the class package (it is null)",
22: cls.getPackage() != null);
23: assertEquals("Class loader defined the wrong package",
24: "test.dynamic", cls.getPackage().getName());
25:
26: Object obj = cls.newInstance();
27: assertEquals("Wrong initial instance count on first load", "1",
28: obj.toString());
29:
30: cl = new NonDelegatingClassLoader(DYNAMIC_CLASSPATH, pcl);
31: cls = Class.forName(className, true, cl);
32: obj = cls.newInstance();
33: assertEquals(
34: "Wrong initial instance count when not delegating",
35: "1", obj.toString());
36: }
37:
38: private class DelegatingClassLoader extends
39: NonDelegatingClassLoader {
40: public DelegatingClassLoader(String path, ClassLoader parent) {
41: super (path, parent);
42: }
43:
44: protected boolean shouldDelegate(String cname) {
45: return true;
46: }
47: }
48:
49: public void testDelegation() throws Throwable {
50: String className = DYNAMIC_CLASSNAME;
51: ClassLoader parent = new PathClassLoader(DYNAMIC_CLASSPATH,
52: getClass().getClassLoader());
53: ClassLoader cl = new DelegatingClassLoader(DYNAMIC_CLASSPATH,
54: parent);
55: Class cls = Class.forName(className, true, cl);
56: Object obj = cls.newInstance();
57: assertEquals("Wrong initial instance count on first load", "1",
58: obj.toString());
59:
60: cl = new DelegatingClassLoader(DYNAMIC_CLASSPATH, parent);
61: cls = Class.forName(className, true, cl);
62: obj = cls.newInstance();
63: assertEquals("Wrong instance count when delegating", "2", obj
64: .toString());
65: }
66:
67: public NonDelegatingClassLoaderTest(String name) {
68: super (name);
69: }
70:
71: public static void main(String[] args) {
72: TestHelper.runTests(args, NonDelegatingClassLoaderTest.class);
73: }
74: }
|