Testing Private method using mockito
It is generally considered bad practice to test private methods, as they are an implementation detail that should not be exposed to the outside world. Private methods are often not designed to be called directly, and they can change without notice, which can break the tests that depend on them.
Instead of testing private methods, it is usually better to test the public methods and the overall behavior of the class. This ensures that the class is correct from the perspective of its users and reduces the risk of breaking the tests when the implementation changes.
If you still want to test a private method, one way to do it is to use reflection to call the method from your test. Here's an example of how you can use reflection to test a private method using Mockito:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner;
import java.lang.reflect.Method;
import static org.junit.Assert.assertEquals;
@RunWith(MockitoJUnitRunner.class)
public class PrivateMethodTest {
@Spy
private MyClass myClass;
@InjectMocks
private MyClassService myClassService;
@Test
public void testPrivateMethod() throws Exception {
Method privateMethod = MyClass.class.getDeclaredMethod("privateMethod");
privateMethod.setAccessible(true);
String result = (String) privateMethod.invoke(myClass);
assertEquals("private method", result);
}
}
class MyClass {
private String privateMethod() {
return "private method";
}
}
class MyClassService {
private final MyClass myClass;
MyClassService(MyClass myClass) {
this.myClass = myClass;
}
}
This code defines a test class PrivateMethodTest
with a spy of the MyClass
class and an instance of the MyClassService
class that depends on it. It also defines a test method testPrivateMethod
that uses reflection to call the privateMethod
method of MyClass
.
To use reflection to call the private method, the code first gets a Method
object for the privateMethod
method using the getDeclaredMethod
method of the Class
object. It then sets the accessible
flag of the Method
object to true
using the setAccessible
method. Finally, it invokes the privateMethod
method using the invoke
method of the Method
object and passes it the instance of MyClass
that it wants to call the method on.
I hope this helps! Let me know if you have any questions.