Testing Private method using mockito


public class A {

    public void method(boolean b){
          if (b == true)

    private void method1() {}
    private void method2() {}
public class TestA {

    public void testMethod() {
      A a = mock(A.class);
      //how to test like    verify(a).method1();

How to test private method is called or not, and how to test private method using mockito???

This question is tagged with java junit mockito

~ Asked on 2012-01-10 06:33:11

The Best Answer is


You can't do that with Mockito but you can use Powermock to extend Mockito and mock private methods. Powermock supports Mockito. Here's an example.

~ Answered on 2012-01-10 06:43:40


Not possible through mockito. From their wiki

Why Mockito doesn't mock private methods?

Firstly, we are not dogmatic about mocking private methods. We just don't care about private methods because from the standpoint of testing private methods don't exist. Here are a couple of reasons Mockito doesn't mock private methods:

It requires hacking of classloaders that is never bullet proof and it changes the api (you must use custom test runner, annotate the class, etc.).

It is very easy to work around - just change the visibility of method from private to package-protected (or protected).

It requires me to spend time implementing & maintaining it. And it does not make sense given point #2 and a fact that it is already implemented in different tool (powermock).

Finally... Mocking private methods is a hint that there is something wrong with OO understanding. In OO you want objects (or roles) to collaborate, not methods. Forget about pascal & procedural code. Think in objects.

~ Answered on 2012-01-10 06:37:05

Most Viewed Questions: