samples/openfixed/test/org/apidesign/openfixed/CalculatorBase.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 30 Oct 2014 21:30:10 +0100
changeset 409 40cabcdcd2be
parent 375 3abae898011d
permissions -rw-r--r--
Updating to NBMs from NetBeans 8.0.1 as some of them are required to run on JDK8
     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     // BEGIN: openfixed.commontest
    16     public void testSumAndListeners() throws Exception {
    17         Calculator a = create();
    18         MockListener l = new MockListener();
    19         a.addModificationListener(l);
    20         a.add(5);
    21         a.add(10);
    22         a.add(20);
    23         int ch = allChanges(l.assertEvents("Three changes", 3));
    24         assertEquals("35 was the change", 35, ch);
    25         assertEquals("Current value", 35, a.getSum());
    26         a.add(-5);
    27         int ch2 = allChanges(l.assertEvents("One change", 1));
    28         assertEquals("minus five was the change", -5, ch2);
    29         assertEquals("Final value", 30, a.getSum());
    30     }
    31     
    32     private static int allChanges(List<ModificationEvent> events) {
    33         int changes = 0;
    34         for (ModificationEvent me : events) {
    35             changes += me.getChange();
    36         }
    37         return changes;
    38     }
    39     
    40     public static class MockListener implements ModificationListener {
    41         private List<ModificationEvent> events;
    42         
    43         @Override
    44         public synchronized void modification(ModificationEvent ev) {
    45             if (events == null) {
    46                 events = new ArrayList<ModificationEvent>();
    47             }
    48             events.add(ev);
    49             notifyAll();
    50         }
    51         
    52         public synchronized List<ModificationEvent> assertEvents(
    53             String msg, int cnt
    54         ) throws InterruptedException {
    55             for (int i = 0; i < 10; i++) {
    56                 if (events != null && events.size() >= cnt) {
    57                     break;
    58                 }
    59                 wait(1000);
    60             }
    61             assertEquals(msg + ":\n" + events, cnt, events.size());
    62             List<ModificationEvent> res = events;
    63             events = null;
    64             return res;
    65         }
    66     } // end of ModificationListener
    67     // END: openfixed.commontest
    68 }