1 package com.tirsen.nanning.locking; 2 3 import com.tirsen.nanning.AspectInstance; 4 import com.tirsen.nanning.MixinInstance; 5 import com.tirsen.nanning.config.AllPointcut; 6 import com.tirsen.nanning.config.Pointcut; 7 import com.tirsen.nanning.config.AspectSystem; 8 import junit.framework.TestCase; 9 10 public class PessimisticLockingAspectTest extends TestCase { 11 private PessimisticLockingAspect lockAspect = new PessimisticLockingAspect() { 12 protected Pointcut lockingPointcut() { 13 return new AllPointcut(); 14 } 15 }; 16 17 public static interface Interface { 18 void method(); 19 } 20 21 private Interface createLockAspectedObject(Interface target) { 22 AspectInstance instance = createLockAspectedInstance(target); 23 return (Interface) instance.getProxy(); 24 } 25 26 private AspectInstance createLockAspectedInstance(Interface target) { 27 AspectInstance instance = new AspectInstance(); 28 instance.addMixin(new MixinInstance(Interface.class, target)); 29 lockAspect.introduce(instance); 30 lockAspect.advise(instance); 31 return instance; 32 } 33 34 private boolean wasCalled; 35 36 public void testAdvise() throws NoSuchMethodException { 37 AspectInstance instance = createLockAspectedInstance(null); 38 assertEquals(1, instance.getAllInterceptors().size()); 39 assertEquals(0, instance.getMixinForInterface(Lockable.class).getAllInterceptors().size()); 40 } 41 42 public void testIntroduce() { 43 PessimisticLockingAspect lockAspect = new PessimisticLockingAspect() { 44 protected Pointcut lockingPointcut() { 45 return new AllPointcut(); 46 } 47 }; 48 AspectInstance instance = createLockAspectedInstance(null); 49 assertEquals(2, instance.getMixins().size()); 50 MixinInstance mixin = instance.getMixinForInterface(Lockable.class); 51 assertNotNull(mixin); 52 assertNotNull(mixin.getTarget()); 53 54 Lockable lockable = (Lockable) instance.getProxy(); 55 lockable.lock(); 56 assertTrue(lockable.isLocked()); 57 } 58 59 public void testCallWithoutLock() { 60 Interface o = createLockAspectedObject( 61 new Interface() { 62 public void method() { 63 wasCalled = true; 64 } 65 }); 66 67 assertFalse(wasCalled); 68 o.method(); 69 assertTrue(wasCalled); 70 } 71 72 public void testCallWithLock() { 73 Interface o = createLockAspectedObject( 74 new Interface() { 75 public void method() { 76 wasCalled = true; 77 } 78 }); 79 80 assertFalse(wasCalled); 81 ((Lockable) o).lock(); 82 try { 83 o.method(); 84 fail(); 85 } catch (LockedException shouldHappen) { 86 } 87 assertFalse(wasCalled); 88 } 89 } 90 | Popular Tags |