samples/openfixed/test/org/apidesign/openfixed/CalculatorBase.java
changeset 374 35da2d439e3d
child 375 3abae898011d
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/samples/openfixed/test/org/apidesign/openfixed/CalculatorBase.java	Sun Mar 20 18:52:47 2011 +0100
     1.3 @@ -0,0 +1,64 @@
     1.4 +package org.apidesign.openfixed;
     1.5 +
     1.6 +import java.util.ArrayList;
     1.7 +import java.util.List;
     1.8 +import junit.framework.TestCase;
     1.9 +
    1.10 +public abstract class CalculatorBase extends TestCase {
    1.11 +    
    1.12 +    public CalculatorBase(String testName) {
    1.13 +        super(testName);
    1.14 +    }
    1.15 +    
    1.16 +    protected abstract Calculator create();
    1.17 +
    1.18 +    public void testSumAndListeners() throws Exception {
    1.19 +        Calculator a = create();
    1.20 +        MockListener l = new MockListener();
    1.21 +        a.addModificationListener(l);
    1.22 +        a.add(5);
    1.23 +        a.add(10);
    1.24 +        a.add(20);
    1.25 +        int ch = allChanges(l.assertEvents("Three changes", 3));
    1.26 +        assertEquals("35 was the change", 35, ch);
    1.27 +        assertEquals("Current value", 35, a.getSum());
    1.28 +        a.add(-5);
    1.29 +        int ch2 = allChanges(l.assertEvents("One change", 1));
    1.30 +        assertEquals("minus five was the change", -5, ch2);
    1.31 +        assertEquals("Final value", 30, a.getSum());
    1.32 +    }
    1.33 +    
    1.34 +    private static int allChanges(List<ModificationEvent> events) {
    1.35 +        int changes = 0;
    1.36 +        for (ModificationEvent me : events) {
    1.37 +            changes += me.getChange();
    1.38 +        }
    1.39 +        return changes;
    1.40 +    }
    1.41 +    
    1.42 +    public static class MockListener implements ModificationListener {
    1.43 +        private List<ModificationEvent> events;
    1.44 +        
    1.45 +        @Override
    1.46 +        public synchronized void modification(ModificationEvent ev) {
    1.47 +            if (events == null) {
    1.48 +                events = new ArrayList<ModificationEvent>();
    1.49 +            }
    1.50 +            events.add(ev);
    1.51 +        }
    1.52 +        
    1.53 +        public synchronized List<ModificationEvent> assertEvents(String msg, int cnt) 
    1.54 +        throws InterruptedException {
    1.55 +            for (int i = 0; i < 10; i++) {
    1.56 +                if (events != null && events.size() >= cnt) {
    1.57 +                    break;
    1.58 +                }
    1.59 +                wait(1000);
    1.60 +            }
    1.61 +            assertEquals(msg + ":\n" + events, cnt, events.size());
    1.62 +            List<ModificationEvent> res = events;
    1.63 +            events = null;
    1.64 +            return res;
    1.65 +        }
    1.66 +    } // end of ModificationListener
    1.67 +}