samples/openfixed/test/org/apidesign/openfixed/CalculatorBase.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sun, 20 Mar 2011 18:52:47 +0100
changeset 374 35da2d439e3d
child 375 3abae898011d
permissions -rw-r--r--
Calculator and various ways to deliver changes in its counter to listeners
     1 package org.apidesign.openfixed;
     2 
     3 import java.util.ArrayList;
     4 import java.util.List;
     5 import junit.framework.TestCase;
     6 
     7 public abstract class CalculatorBase extends TestCase {
     8     
     9     public CalculatorBase(String testName) {
    10         super(testName);
    11     }
    12     
    13     protected abstract Calculator create();
    14 
    15     public void testSumAndListeners() throws Exception {
    16         Calculator a = create();
    17         MockListener l = new MockListener();
    18         a.addModificationListener(l);
    19         a.add(5);
    20         a.add(10);
    21         a.add(20);
    22         int ch = allChanges(l.assertEvents("Three changes", 3));
    23         assertEquals("35 was the change", 35, ch);
    24         assertEquals("Current value", 35, a.getSum());
    25         a.add(-5);
    26         int ch2 = allChanges(l.assertEvents("One change", 1));
    27         assertEquals("minus five was the change", -5, ch2);
    28         assertEquals("Final value", 30, a.getSum());
    29     }
    30     
    31     private static int allChanges(List<ModificationEvent> events) {
    32         int changes = 0;
    33         for (ModificationEvent me : events) {
    34             changes += me.getChange();
    35         }
    36         return changes;
    37     }
    38     
    39     public static class MockListener implements ModificationListener {
    40         private List<ModificationEvent> events;
    41         
    42         @Override
    43         public synchronized void modification(ModificationEvent ev) {
    44             if (events == null) {
    45                 events = new ArrayList<ModificationEvent>();
    46             }
    47             events.add(ev);
    48         }
    49         
    50         public synchronized List<ModificationEvent> assertEvents(String msg, int cnt) 
    51         throws InterruptedException {
    52             for (int i = 0; i < 10; i++) {
    53                 if (events != null && events.size() >= cnt) {
    54                     break;
    55                 }
    56                 wait(1000);
    57             }
    58             assertEquals(msg + ":\n" + events, cnt, events.size());
    59             List<ModificationEvent> res = events;
    60             events = null;
    61             return res;
    62         }
    63     } // end of ModificationListener
    64 }