1 19 20 package asm1; 21 22 import java.io.IOException ; 23 import java.util.ArrayList ; 24 import java.util.List ; 25 26 import junit.framework.TestCase; 27 28 import org.objectweb.asm.ClassReader; 29 import org.objectweb.asm.ClassWriter; 30 31 32 public class NotifierClassVisitorTest extends TestCase { 33 private static final String TEST_CLASS = "asm1.Counter1"; 34 35 private TestListener listener; 36 private Counter counter; 37 38 39 public void setUp() throws Exception { 40 super.setUp(); 41 42 listener = new TestListener(); 43 44 Class cc = loadClass(TEST_CLASS); 45 counter = ( Counter) cc.newInstance(); 46 47 (( Notifier) counter).addListener( listener); 48 } 49 50 51 public void testCounter() { 52 int n1 = counter.count(); 53 counter.increment(); 54 int n2 = counter.count(); 55 assertEquals( n1+1, n2); 56 } 57 58 public void testNotifier() { 59 counter.count(); 60 counter.increment(); 61 counter.count(); 62 63 List events = listener.getEvents(); 64 assertEquals( 3, events.size()); 65 } 66 67 68 private Class loadClass(final String className) throws ClassNotFoundException { 69 ClassLoader cl = new TestClassLoader(getClass().getClassLoader(), className); 70 return cl.loadClass(className); 71 } 72 73 74 private static final class TestClassLoader extends ClassLoader { 75 private final String className; 76 private final ClassLoader cl; 77 78 public TestClassLoader(ClassLoader cl, String className) { 79 super(); 80 this.cl = cl; 81 this.className = className; 82 } 83 84 public Class loadClass(String name) throws ClassNotFoundException { 85 if( className.equals(name)) { 86 try { 87 byte[] bytecode = transformClass( className); 88 return super.defineClass( className, bytecode, 0, bytecode.length); 89 90 } catch( IOException ex) { 91 throw new ClassNotFoundException ( "Load error: "+ex.toString(), ex); 92 93 } 94 } 95 return cl.loadClass( name); 96 } 97 98 private byte[] transformClass( String className) throws IOException { 99 ClassWriter cw = new ClassWriter( true, true); 100 NotifierClassVisitor ncv = new NotifierClassVisitor( cw); 101 102 ClassReader cr = new ClassReader( getClass().getResourceAsStream( "/"+className.replace('.','/')+".class")); 103 cr.accept( ncv, false); 104 return cw.toByteArray(); 105 } 106 107 } 108 109 110 private static final class TestListener implements Listener { 111 private List events = new ArrayList (); 112 113 public void notify( Object src, Object msg) { 114 events.add( new Object [] { src, msg}); 115 } 116 117 public List getEvents() { 118 return events; 119 } 120 121 } 122 123 } 124 125 | Popular Tags |