public class A { public void method(boolean b){ if (b == true) method1(); else method2(); } private void method1() {} private void method2() {} }
public class TestA { @Test public void testMethod() { A a = mock(A.class); a.method(true); //how to test like verify(a).method1(); } }
How to test private method is called or not, and how to test private method using mockito???
You're not suppose to test private methods. Only non-private methods needs to be tested as these should call the private methods anyway. If you "want" to test private methods, it may indicate that you need to rethink your design:
Am I using proper dependency injection? Do I possibly needs to move the private methods into a separate class and rather test that? Must these methods be private? ...can't they be default or protected rather?
In the above instance, the two methods that are called "randomly" may actually need to be placed in a class of their own, tested and then injected into the class above.
Put your test in the same package, but a different source folder (src/main/java vs. src/test/java) and make those methods package-private. Imo testability is more important than privacy.
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.
Here is a small example how to do it with powermock
To test method1 use code:
To set private object obj use this:
There is actually a way to test methods from a private member with Mockito. Let's say you have a class like this:
If you want to test
a.method
will invoke a method fromSomeOtherClass
, you can write something like below.ReflectionTestUtils.setField();
will stub the private member with something you can spy on.