How would you test private methods in JUnit? Should you test them directly?

Private methods generally shouldn't be tested directly in JUnit; instead, they should be exercised indirectly through the public methods that call them, since tests should target a class's observable behavior.

Key Points: • JUnit has no built-in mechanism to call private methods, so testing them directly requires reflection, which is fragile and discouraged. • Testing through public methods keeps tests aligned with how the class is actually used and refactor-resistant. • If a private method has complex logic that's hard to reach through the public API, that's often a sign it deserves to be extracted into its own testable class. • Some frameworks or reflection utilities (e.g. Spring's ReflectionTestUtils) can invoke private methods when truly necessary, but this should be rare. • Testing implementation details rather than behavior tends to produce brittle tests that break on harmless refactors.

Example: If a Calculator class has a private roundToTwoDecimals() helper used inside its public calculateTotal() method, you test it by asserting on calculateTotal()'s output rather than reflecting into the private helper directly.

Interview Tip: A concise interview answer is:

"I don't test private methods directly - I test them indirectly through the public methods that use them, since tests should verify observable behavior, not implementation details. If a private method is complex enough to need its own dedicated tests, that usually means it should be extracted into its own class."