In unit testing with JUnit, why is it generally discouraged to test private methods directly?
Think about what private methods represent in object-oriented design.
Private methods are internal helpers. Testing them directly exposes internal details and makes tests fragile. Instead, test the public methods that use them.
What will happen if you try to call a private method directly from a JUnit test class without using reflection?
public class Calculator { private int add(int a, int b) { return a + b; } } public class CalculatorTest { @Test public void testAdd() { Calculator calc = new Calculator(); int result = calc.add(2, 3); // Direct call to private method } }
Consider Java access modifiers and compile-time checks.
Private methods cannot be accessed outside their class. Trying to call them directly from test code causes a compile-time error.
Which code snippet correctly uses Java reflection to invoke a private method calculate with no parameters in a class MathUtils inside a JUnit test?
Remember that private methods require getDeclaredMethod and setAccessible(true).
Private methods are not accessible via getMethod which only returns public methods. You must use getDeclaredMethod and then set accessibility to true before invoking.
After invoking a private method computeSum via reflection that returns an int, which JUnit assertion correctly verifies the result equals 10?
Method method = MyClass.class.getDeclaredMethod("computeSum", int.class, int.class); method.setAccessible(true); int result = (int) method.invoke(new MyClass(), 4, 6);
Check the order of parameters in assertEquals.
In JUnit, the expected value comes first, then the actual value. Using assertEquals(10, result) is correct.
In Test-Driven Development (TDD), what is the best practice regarding testing private methods?
Think about how TDD focuses on behavior rather than implementation.
TDD encourages testing behavior through the public API. Private methods are implementation details and should be tested only indirectly.