Complete the code to create a JUnit test method that tests a public method.
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class CalculatorTest { @Test void testAdd() { Calculator calc = new Calculator(); int result = calc.add(2, 3); assertEquals([1], result); } }
The add method should return the sum of 2 and 3, which is 5.
Complete the code to use reflection to access a private method named 'calculate' in a test.
import org.junit.jupiter.api.Test; import java.lang.reflect.Method; import static org.junit.jupiter.api.Assertions.*; class CalculatorTest { @Test void testPrivateCalculate() throws Exception { Calculator calc = new Calculator(); Method method = Calculator.class.getDeclaredMethod("calculate", int.class, int.class); method.setAccessible(true); int result = (int) method.invoke(calc, 4, 5); assertEquals([1], result); } }
The private method 'calculate' is expected to return the sum of 4 and 5, which is 9.
Fix the error in the test code that tries to test a private method directly.
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class CalculatorTest { @Test void testPrivateMethod() { Calculator calc = new Calculator(); // This line causes a compile error because 'calculate' is private int result = calc.[1](3, 7); assertEquals(10, result); } }
You cannot call a private method directly. Instead, test a public method like 'add' that uses the private method internally.
Fill both blanks to complete the explanation about testing private methods.
/* It is generally recommended to test [1] methods instead of private methods directly. * Private methods should be tested indirectly through [2] methods. */
Testing public methods ensures private methods are tested indirectly, keeping tests maintainable.
Fill all three blanks to complete the code snippet that uses reflection safely to test a private method.
import org.junit.jupiter.api.Test; import java.lang.reflect.Method; import static org.junit.jupiter.api.Assertions.*; class CalculatorTest { @Test void testPrivateMethodReflection() throws Exception { Calculator calc = new Calculator(); Method method = Calculator.class.getDeclaredMethod("[1]", int.class, int.class); method.[2](true); int result = (int) method.invoke(calc, [3], 8); assertEquals(13, result); } }
The private method 'calculate' is accessed by setting it accessible, then invoked with arguments 5 and 8.