1 6 package org.logicalcobwebs.proxool.util; 7 8 import org.logicalcobwebs.proxool.AbstractProxoolTest; 9 10 18 public class ListenerContainerTest extends AbstractProxoolTest { 19 20 23 public ListenerContainerTest(String name) { 24 super(name); 25 } 26 27 30 public void testAdd() { 31 CompositeTestListener compositeTestListener = new CompositeTestListener(); 32 for (int i = 0; i < 10; ++i) { 33 compositeTestListener.addListener(new TestListener()); 34 } 35 compositeTestListener.onEvent(); 36 assertTrue("Only got " + compositeTestListener.getNumberOfNotifications() 37 + " notifications but expected 10.", compositeTestListener.getNumberOfNotifications() == 10); 38 } 39 40 44 public void testRemove() { 45 TestListenerIF[] testListeners = new TestListenerIF[]{ 46 new TestListener(), new TestListener(), new TestListener(), new TestListener(), 47 new TestListener(), new TestListener(), new TestListener(), new TestListener(), 48 new TestListener(), new TestListener() 49 }; 50 CompositeTestListener compositeTestListener = new CompositeTestListener(); 51 for (int i = 0; i < 10; ++i) { 52 compositeTestListener.addListener(testListeners[i]); 53 } 54 for (int i = 0; i < 10; ++i) { 55 assertTrue("Removal of a listener failed.", compositeTestListener.removeListener(testListeners[i])); 56 } 57 assertTrue("Removal of unregistered listener returned true", 58 !compositeTestListener.removeListener(new TestListener())); 59 compositeTestListener.onEvent(); 60 assertTrue("Listeners was notified even if all listeners had been removed.", 61 compositeTestListener.getNumberOfNotifications() == 0); 62 } 63 64 } 65 66 interface TestListenerIF { 67 void onEvent(); 68 } 69 70 class CompositeTestListener extends AbstractListenerContainer implements TestListenerIF { 71 private int numberOfNotifications; 72 73 public void onEvent() { 74 Object [] listeners = getListeners(); 75 76 for(int i=0; i<listeners.length; i++) { 77 TestListenerIF testListener = (TestListenerIF) listeners[i]; 78 notification(); 79 } 80 } 81 82 int getNumberOfNotifications() { 83 return numberOfNotifications; 84 } 85 86 private synchronized void notification() { 87 numberOfNotifications++; 88 } 89 } 90 91 class TestListener implements TestListenerIF { 92 public void onEvent() { 93 } 94 } 95 96 120 | Popular Tags |