Monday, June 28, 2010

How to suppress fields with PowerMock

Now why would you want to do that! Lets look at the code straightaway.

Code under test:

The AccountDAO class has a "session" field, which has been initialized where its declared. Assuming that Session class in our example, is a wrapper over the the Hibernate Session class which talks to the database and does stuff for us.

BTW I couldn't agree more that its a terrible design!

So, basically what we want is to suppress the field "session" and instead use a stubbed Session instance.   Which means, we would stub out the getSession method, to write good unit-test case for the findAccount method.

So how do we suppress the field "session"

How would we test it - How do they do it!

The suppress method (which we had a look in the earlier post) can not only suppress the methods but can also suppress fields.

The Syntax:

What does the above syntax mean? Just read the line in plain English and that is exactly what it means!

Suppress the field of AccountDAO class called "session"

After this statement if we call getSession on any instance of AccountDAO it will always return null.

Q: But how can PowerMock do it?
A: Via byte code manipulation.  Remember our old friend @PrepareForTest(AccountDAO.class) annotation.

So we have solved one part of the problem. The next problem is to return a stubbed session instance when getSession method of AccountDAO is called. How can we do that?
A: Remember partial mocks via the spy method

That makes the problem look much simpler right?

So lets look at the test code:

Yes! We have managed to suppress a field for any given class.

Really, PowerMock's (using the Mockito api) keeps dazzling us with its Power!
Have some Fun!