'Mocking a public method that has a private method call inside using Mockito (not Powermockito)

I am testing for methodA() in the class :

class Test{
 public String methodA(String str){
  ...
  methodB("s1","s2");
  ...
 }
 private String methodB(String s1, String s2){
   ...
 }
}

What I have tried in my test class:

Method methodBReflect = Test.class.getDeclaredMethod("methodB", Test.class,String.class, String.class);
methodBReflect.setAccessible(true);
Test testForSpy=new Test();
Test spyTest=spy(testForSpy);
doReturn("return string").when(spyTest..)... // <-- What should be done here?
//methodBReflect.invoke(spyTest, "args1","args2");

P.S: I don't need a solution using powermock as I have some organizational constraints using it.



Solution 1:[1]

You shouldn't be testing that method A calls method B. You should test that method A does what method A is supposed to do - that is, it gives the correct output for whatever input you give it. Your test shouldn't care whether method A works by calling method B, or by doing all its processing inline.

Therefore, there's no need to mock or stub anything. Your tests will consist of a bunch of calls to method A, along with verification that the output is what you expect.

You only need to use Mockito (or some other mocking framework) when you're testing a class that interacts with another class entirely; not when the class under test interacts with itself.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dawood ibn Kareem