File size: 1,896 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.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class FractionTest {
@Test void reducesAndNormalizesSign() {
Fraction f = new Fraction(4, -8);
assertEquals(-1, f.numerator());
assertEquals(2, f.denominator());
assertEquals("-1/2", f.toString());
}
@Test void wholeNumberToString() { assertEquals("3", new Fraction(6, 2).toString()); }
@Test void zeroIsZeroOverOne() {
Fraction z = new Fraction(0, 5);
assertEquals(0, z.numerator());
assertEquals(1, z.denominator());
}
@Test void zeroDenominator() { assertThrows(ArithmeticException.class, () -> new Fraction(1, 0)); }
@Test void add() { assertEquals(new Fraction(5, 6), new Fraction(1, 2).add(new Fraction(1, 3))); }
@Test void subtract() { assertEquals(new Fraction(1, 6), new Fraction(1, 2).subtract(new Fraction(1, 3))); }
@Test void multiply() { assertEquals(new Fraction(1, 6), new Fraction(1, 2).multiply(new Fraction(1, 3))); }
@Test void divide() { assertEquals(new Fraction(3, 2), new Fraction(1, 2).divide(new Fraction(1, 3))); }
@Test void divideByZero() { assertThrows(ArithmeticException.class, () -> new Fraction(1, 2).divide(new Fraction(0, 3))); }
@Test void toDouble() { assertEquals(0.75, new Fraction(3, 4).toDouble(), 1e-12); }
@Test 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 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");
}
}
|