Reputation: 306
Class Calculate{
private int Add(int a, int b){
return a+b;
}
}
Class TestCalculate{
//Here I want to mock the Calculate to invoke the add method.
}
Can you please suggest how to invoke private method using Powermock in above scenario?
Upvotes: 0
Views: 361
Reputation: 10662
There are many different opinions to testing private methods. You can make an argument for not doing it, but, especially for more complex private methods, you can also make an argument for doing it. You will find a nice discussion over at programmers.
Assuming you actually still want to do it (and not refactor your code or test only your public api), it's actually quite simple with PowerMock, see here:
Calculate calc = new Calculate();
int sum = Whitebox.<Integer> invokeMethod(calc , "Add", 1, 2);
assertThat(sum, equalTo(3)); // using static imports here
(Please note that generally, method names should start with a lowercase character, so the better name here would be add
instead of Add
.)
It is also easy enough to do even without PowerMock, since reflection lets you find and call private methods, but that's outside the scope of this question (and PowerMock allows you to do that with a single statement).
Upvotes: 1