Test Overview
This test checks the behavior of a public method that internally uses a private method. It verifies the final output without directly testing the private method, following best practices.
This test checks the behavior of a public method that internally uses a private method. It verifies the final output without directly testing the private method, following best practices.
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; class Calculator { private int doubleValue(int x) { return x * 2; } public int tripleDouble(int x) { return doubleValue(x) * 3; } } public class CalculatorTest { @Test void testTripleDouble() { Calculator calc = new Calculator(); int result = calc.tripleDouble(4); assertEquals(24, result, "tripleDouble should return doubleValue times 3"); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | JUnit test runner initialized | — | PASS |
| 2 | CalculatorTest creates Calculator instance | Calculator object ready | — | PASS |
| 3 | Calls public method tripleDouble(4) | Inside Calculator.tripleDouble method | — | PASS |
| 4 | tripleDouble calls private method doubleValue(4) | Inside Calculator.doubleValue method | — | PASS |
| 5 | doubleValue returns 8 | Back in tripleDouble method | — | PASS |
| 6 | tripleDouble returns 8 * 3 = 24 | Result ready for assertion | Check if result equals 24 | PASS |
| 7 | JUnit asserts result == 24 | Test assertion executed | assertEquals(24, result) | PASS |
| 8 | Test ends successfully | Test passed | — | PASS |
public class Calculator {
private int multiply(int a, int b) {
return a * b;
}
public int square(int x) {
return multiply(x, x);
}
}multiply method's behavior without accessing it directly?multiply method is private and cannot be called directly in tests.square method calls multiply internally, so testing square indirectly tests multiply.Method method = Calculator.class.getDeclaredMethod("multiply", int.class, int.class);
method.setAccessible(true);
int result = (int) method.invoke(new Calculator(), 2, 3);
Assert.assertEquals(6, result);Pass the test and this pattern moves unknown