1   package com.diasparsoftware.java.util.test;
2   
3   import java.math.BigDecimal;
4   
5   import junit.framework.TestCase;
6   
7   import com.diasparsoftware.java.util.Quantity;
8   import com.gargoylesoftware.base.testing.TestUtil;
9   
10  public class QuantityTest extends TestCase {
11      public void testAdd() {
12          Quantity first = new Quantity(new Integer(3), "CAD");
13          Quantity second = new Quantity(new Integer(4), "CAD");
14  
15          assertEquals(
16              new Quantity(new Integer(7), "CAD"),
17              first.add(second));
18      }
19  
20      public void testAddDifferentUnits() {
21          Quantity first = new Quantity(new Integer(3), "CAD");
22          Quantity second = new Quantity(new Integer(4), "USD");
23  
24          try {
25              first.add(second);
26              fail("Added quantities with different units?!");
27          }
28          catch (ClassCastException expected) {
29          }
30      }
31  
32      public void testZeroOf() {
33          Quantity zero = Quantity.zeroOf("XXX");
34          assertEquals(new Quantity(new BigDecimal(0), "XXX"), zero);
35      }
36  
37      public void testSerialization() throws Exception {
38          Quantity quantity = new Quantity(new Integer(5), "kg");
39          TestUtil.testSerialization(quantity, true);
40      }
41  
42      public void testAddSubclass() throws Exception {
43          MeterQuantity addend = new MeterQuantity(5);
44          MeterQuantity augend = new MeterQuantity(10);
45  
46          Quantity sum = addend.add(augend);
47          assertTrue(
48              "Sum is of the wrong type; subclass does not override clone()",
49              sum instanceof MeterQuantity);
50              
51          assertEquals(new MeterQuantity(15), sum);
52      }
53  
54      public static class MeterQuantity extends Quantity {
55          public MeterQuantity(int magnitude) {
56              super(new BigDecimal(magnitude), "m");
57          }
58  
59          public Object clone() {
60              return new MeterQuantity(magnitude.intValue());
61          }
62      }
63  }