File size: 1,941 Bytes
63f6453
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import org.junit.Test;
import static org.junit.Assert.*;

public class FractionTest {
    @Test public void reducesAndNormalizesSign() {
        Fraction f = new Fraction(4, -8);
        assertEquals(-1, f.numerator());
        assertEquals(2, f.denominator());
        assertEquals("-1/2", f.toString());
    }
    @Test public void wholeNumberToString() { assertEquals("3", new Fraction(6, 2).toString()); }
    @Test public void zeroIsZeroOverOne() {
        Fraction z = new Fraction(0, 5);
        assertEquals(0, z.numerator());
        assertEquals(1, z.denominator());
    }
    @Test(expected = ArithmeticException.class) public void zeroDenominator() { new Fraction(1, 0); }
    @Test public void add() { assertEquals(new Fraction(5, 6), new Fraction(1, 2).add(new Fraction(1, 3))); }
    @Test public void subtract() { assertEquals(new Fraction(1, 6), new Fraction(1, 2).subtract(new Fraction(1, 3))); }
    @Test public void multiply() { assertEquals(new Fraction(1, 6), new Fraction(1, 2).multiply(new Fraction(1, 3))); }
    @Test public void divide() { assertEquals(new Fraction(3, 2), new Fraction(1, 2).divide(new Fraction(1, 3))); }
    @Test(expected = ArithmeticException.class) public void divideByZero() { new Fraction(1, 2).divide(new Fraction(0, 3)); }
    @Test public void toDouble() { assertEquals(0.75, new Fraction(3, 4).toDouble(), 1e-12); }
    @Test public void compare() {
        assertTrue(new Fraction(1, 3).compareTo(new Fraction(1, 2)) < 0);
        assertTrue(new Fraction(2, 3).compareTo(new Fraction(1, 2)) > 0);
        assertEquals(0, new Fraction(2, 4).compareTo(new Fraction(1, 2)));
    }
    @Test public void equalsAndHashCode() {
        Fraction a = new Fraction(2, 4), b = new Fraction(1, 2);
        assertEquals(a, b);
        assertEquals(a.hashCode(), b.hashCode());
        assertEquals(a, a);
        assertNotEquals(a, new Fraction(1, 3));
        assertNotEquals(a, "1/2");
    }
}