Sunday, August 29, 2010

How to mock/stub void methods using PowerMock

Ok, I had though that the previous post would be the last post in the how-to series, but there are so many features in PowerMock that I am tempted to write more about it :)

So, here comes another post on how to mock/stub void methods using PowerMock.

One would think why are void methods so special, that we need a post to explain them?

Well thats because they are void methods. They don't return anything. If you remember, from my earlier post, the syntax of stubbing any method with a non void return type is as follows

In the above example doSomething method of ServiceA instance returns a String.

But imagine what will be the syntax, if doSomething method's return type was void!

May be something like this?

But, if you think for a moment about the above syntax, we would realize that  

methods in java are not very happy to accept void as the argument type!

Effectively, in the above syntax the when method is taking void as one of the argument!

Well this is a problem. This cannot happen!  Hence, we need a special syntax to mock/stub void methods.

So without wasting any more time lets look at the code under test:

In our example we want to test the persistCustomer method of the CustomerController. This method simply calls persist method on the Customer instance passed as argument. Assuming that the persist method of the Customer class returns nothing if everything is fine and throws a RuntimeException if something horribly goes wrong.

We want to write the test case for both these scenarios. So how do we do it?

How will we test it - How do they do it!:

Well, there is always a way with PowerMock!

Our first scenario is to verify that the persistCustomer method returns true if everything goes fine.

PowerMock uses the following syntax to stub the void method to do nothing.

If we read the syntax in pure English it says,

Do nothing when persist method is invoked on customer instance

As simple as that! We are telling the mock customer object to do nothing when persist method is invoked.

Lets look at the test case:

Now the other scenario, we want to make sure that false is returned when an exception is thrown from the persist method of customer instance, but for that to happen we have to stub the persist method of customer to throw an exception.

This is how we do it:

Syntax in English:

Throw RuntimeException when persist method of customer instance is invoked.

Lets look at the test case:

Thats it! Well you see there always is an easy solution with PowerMock
Have some Fun!