I am trying to unit test a method using JUnit4. The method under test is calling another private method and I would like to mock it using PowerMockito.
My method is like below:
Class MyClass {
public List<String> myMethod(String name) throws IOException
{
... Few lines of code for setting variables
List<String> result = myPrivateMethod(a, b);
... Few more lines of code..
result.addAll(myPrivateMethod(c, d));
return result;
}
private List<String> myPrivateMethod(String a, String b) {
.....
}
}
My unit test method to test above code is as below:
@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class)
public class TestClass {
@Test
public void testMyMethod() throws Exception {
MyClass myClass = PowerMockito.spy(new MyClass());
PowerMockito.doReturn(new ArrayList<String>(){{add("temp");}}).when(myClass, "myPrivateMethod", "a", "b");
List<String> list = myClass.myMethod("someName");
assertEquals(list.size(), 1);
}
}
I am expecting line PowerMockito.doReturn(new ArrayList(){{add("temp");}}).when(myClass, "myPrivateMethod", "a", "b"); to return list of size 1. I verified that execution is not going into private method but I am not getting List with one value added.
What is wrong in the above unit test code and why I am getting null instead of populated List as metioned in PowerMockito.doReturn() method?