0
0
JUnittesting~15 mins

Testing private methods (should you?) in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify behavior of a public method that uses a private method internally
Preconditions (1)
Step 1: Create an instance of the class
Step 2: Call the public method with a specific input
Step 3: Observe the output or behavior influenced by the private method
✅ Expected Result: The public method returns the expected result that depends on the private method's logic
Automation Requirements - JUnit 5
Assertions Needed:
Assert the public method returns the expected value influenced by the private method
Best Practices:
Test only public methods, not private methods directly
Use assertions to verify outputs or side effects
Avoid reflection or changing access modifiers to test private methods
Automated Solution
JUnit
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.

Common Mistakes - 3 Pitfalls
Trying to test private methods directly using reflection
Changing private methods to public just to test them
Not asserting expected results and only calling methods
Bonus Challenge

Now add tests for the public method with multiple input values using parameterized tests

Show Hint