A popular open-source testing framework for Java:
src/test/java directoryFraction.java
public class Fraction {
@Getter private int numerator;
@Getter private int denominator;
public Fraction(int numerator, int denominator) {
if (denominator == 0)
throw new IllegalArgumentException("Denominator cannot be zero.");
this.numerator = numerator;
this.denominator = denominator;
}
public Fraction invert() {
if (numerator == 0)
throw new ArithmeticException("Cannot invert a fraction with a zero numerator.");
return new Fraction(denominator, numerator);
}
}FractionTest.java
public class FractionTest {
@Test
void testInvertValid() {
// GIVEN
Fraction fraction = new Fraction(2, 3);
// WHEN
Fraction inverted = fraction.invert();
// THEN
assertEquals(3, inverted.getNumerator());
assertEquals(2, inverted.getDenominator());
}
@Test
void testInvertZeroNumerator() {
Fraction fraction = new Fraction(0, 5);
assertThrows(ArithmeticException.class, fraction::invert);
}
}@Test: Marks a method as a test case@BeforeEach: Executes before each test method@AfterEach: Executes after each test method@BeforeAll: Executes once before all test methods@AfterAll: Executes once after all test methodsFraction.java
@AllArgsConstructor
public class Fraction {
private int numerator;
private int denominator;
private MathService mathService;
public Fraction simplify() {
int gcd = this.mathService.pgcd(numerator, denominator);
return new Fraction(
this.numerator / gcd,
this.denominator / gcd,
this.mathService);
}
}FractionTest.java
class FractionTest {
@Test
void simplifyMockingPgcdMethodCall() {
// GIVEN
MathService mathService = mock(MathService.class);
when(mathService.pgcd(6, 8)).thenReturn(2);
Fraction f = new Fraction(6, 8, mathService);
// WHEN
Fraction result = f.simplify();
// THEN
assertEquals(3, result.getNumerator());
assertEquals(4, result.getDenominator());
verify(mathService).pgcd(6, 8); // Verify it was called one time
}
}FractionTest.java
Let’s introduce a mutation in the code:
Code Coverage ≠ Test quality
+ with - or > with >=