Verify behavior of a public method that uses a private method internally
Preconditions (1)
✅ Expected Result: The public method returns the expected result that depends on the private method's logic
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; class Calculator { private int multiplyByTwo(int number) { return number * 2; } public int doubleAndAddThree(int number) { return multiplyByTwo(number) + 3; } } public class CalculatorTest { @Test void testDoubleAndAddThree() { Calculator calculator = new Calculator(); int input = 5; int expected = 13; // (5 * 2) + 3 = 13 int actual = calculator.doubleAndAddThree(input); assertEquals(expected, actual, "The public method should return correct result based on private method logic"); } }
This test class CalculatorTest tests the public method doubleAndAddThree of the Calculator class.
The private method multiplyByTwo is not tested directly. Instead, we verify the public method's output, which depends on the private method.
This approach follows best practices by testing behavior through public interfaces, avoiding fragile tests that depend on private implementation details.
Now add tests for the public method with multiple input values using parameterized tests
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