“I HAVE THE POWER!!” – I had this feeling a few days ago. I will be honest that at work I do not get time to write unit test cases for each and every piece of code that I write. Often when I do have time, I make an effort to write test cases even for the trivial piece of code blocks such as — Check if properties file is present.
I was working on new code where I had the luxury to write the code in peace (a rarity at my work place where every project is like a fire drill). While writing test cases I came across a situation where I had a class with two methods:
|
|
I wanted to write test cases for both the method. However Junit would not allow me to write a test case for a private method. I searched over internet forums and every one suggested that I use Java Reflection API to write my test cases or make my private method public, which I did not want to do.
That’s when POWERMOCK steps in and in a tiny little section of its documentation I noticed a piece of “**WhiteboxImpl” ** class which can help me test private methods.
So that’s what I am going to demonstrate in this tutorial.
STEP 1: Add Maven jar files
|
|
STEP 2: Create a class MyClass.java
|
|
STEP 3: Write a test case for public method : my _public _method
|
|
As you can see above that there is no issue with calling a public method and it will run successfully but when you try and call the private method, the code will show error that private method is not visible.
STEP 4: Use PowerMock’s WhiteboxImpl class to test a private method.
Before you do anything you need to make sure that you added Powermock annotations correctly.
- Add these two annotations to your class.
[java]
@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class)
[/java]
- Write the code to test private method.
|
|
The syntax is pretty simple WhiteboxImpl.invokeMethod(
The WhiteBoxImpl class actually uses “Java Reflection API” in the background to make a call, but for the lazy coders like me, who do not want to write Reflection API(Read hate Reflection API), the WhiteBoxImpl class is a small piece of coding heaven.
Now run the test class and you will see that test cases have passed.
~Ciao –Repeat the mantra – “I HAVE THE POWER{MOCK}!!!”