Test Overview
This test checks if all methods in a simple Calculator class are called during testing. It verifies test completeness by measuring code coverage.
This test checks if all methods in a simple Calculator class are called during testing. It verifies test completeness by measuring code coverage.
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; class Calculator { int add(int a, int b) { return a + b; } int subtract(int a, int b) { return a - b; } } public class CalculatorTest { @Test void testAdd() { Calculator calc = new Calculator(); int result = calc.add(5, 3); assertEquals(8, result); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | JUnit test runner initializes | — | PASS |
| 2 | CalculatorTest.testAdd() method is called | Calculator instance created | — | PASS |
| 3 | Calculator.add(5, 3) method is called | Inside add method, parameters a=5, b=3 | — | PASS |
| 4 | add method returns 8 | Return value 8 passed back to testAdd | — | PASS |
| 5 | testAdd asserts result equals 8 | Assertion compares expected 8 with actual 8 | assertEquals(8, result) | PASS |
| 6 | Test ends | Test runner completes testAdd | — | PASS |
| 7 | Coverage report generated | Report shows add method covered, subtract method not covered | Coverage measures which methods ran during tests | PASS |
calculate?
public class Calculator {
public int calculate(int x) {
if (x > 0) return x * 2;
else return 0;
}
}
@Test
public void testCalculatePositive() {
Calculator c = new Calculator();
assertEquals(4, c.calculate(2));
}isValid:
public boolean isValid(int n) {
if (n > 0) return true;
else return false;
}
@Test
public void testIsValid() {
assertTrue(isValid(1));
}public String classify(int age) {
if (age < 13) return "child";
else if (age < 20) return "teen";
else return "adult";
}
To achieve 100% coverage, which set of test inputs should you include in your JUnit tests?Pass the test and this pattern moves unknown