import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class Calculator {
public int divide(int a, int b) {
if (b == 0) {
throw new IllegalArgumentException("Divider cannot be zero");
}
return a / b;
}
}
public class CalculatorTest {
private final Calculator calculator = new Calculator();
@Test
void divide_withValidInputs_returnsQuotient() {
int result = calculator.divide(10, 2);
assertEquals(5, result, "10 divided by 2 should be 5");
}
@Test
void divide_withZeroDivider_throwsException() {
assertThrows(IllegalArgumentException.class, () -> calculator.divide(10, 0), "Divider zero should throw exception");
}
}
The Calculator class has a divide method that checks if the divider is zero and throws an exception if so. Otherwise, it returns the division result.
The test class CalculatorTest has two tests: one to check normal division and one to check that dividing by zero throws the correct exception.
Using assertEquals verifies the correct output, and assertThrows verifies the exception. This covers all lines and branches in the divide method.
Running these tests with a coverage tool like Jacoco will show 100% line and branch coverage because both the true and false paths of the if statement are tested.