0
0
JUnittesting~10 mins

Testing private methods (should you?) in JUnit - Test Execution Trace

Choose your learning style9 modes available
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.

Test Code - JUnit
JUnit
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");
    }
}
Execution Trace - 8 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initialized-PASS
2CalculatorTest creates Calculator instanceCalculator object ready-PASS
3Calls public method tripleDouble(4)Inside Calculator.tripleDouble method-PASS
4tripleDouble calls private method doubleValue(4)Inside Calculator.doubleValue method-PASS
5doubleValue returns 8Back in tripleDouble method-PASS
6tripleDouble returns 8 * 3 = 24Result ready for assertionCheck if result equals 24PASS
7JUnit asserts result == 24Test assertion executedassertEquals(24, result)PASS
8Test ends successfullyTest passed-PASS
Failure Scenario
Failing Condition: The public method tripleDouble returns incorrect value due to private method logic error
Execution Trace Quiz - 3 Questions
Test your understanding
Why does the test call the public method instead of the private method directly?
ABecause public methods are faster to test
BBecause private methods do not contain any logic
CBecause private methods cannot be accessed directly from tests
DBecause the test framework only supports public methods
Key Result
Test the public behavior of a class rather than private methods directly. Private methods are implementation details and should be tested indirectly through public methods.