bookmark_borderEasyMock Class Extension – IllegalStateException on expect method

When I write unit tests, I find using EasyMock extremely helpful. Especially using EasyMock Class Extensions give me the ability to mock objects which do not have an interface, or objects that are so legacy (and untested) that I don’t dare to touch them yet.

I say “yet” , because once I have reduced this ‘fear to break things’ factor by writing enough tests to ensure the legacy code works as it should, I *will* touch them.

One little piece of advice when writing your test, is that the ‘expect’ method will throw an exception when you tend to do that on methods that are final.

This might give you an IllegalStateException with the message : “no last call on a mock available”.

This basically means “Help I could not mock this call, and now you want me to mock it anyway!”.

Step back a bit and think how this EasyMock Class Extension would work in order to Mock existing classes? What would you do? Yes, you would extend this class, and override the methods!

That is what the EasyMock Class Extension does. So what happens when you make a method final? You cannot override it!

If you have any IllegalStateException from the EasyMock Class Extension, check your methods you tend to ‘expect’ (override) if they are marked “final”.

Remove the “final” keyword and you will be able to continue your work.

I’ll leave the question : “Should i just remove this ‘final’ keyword?” to your own wisdom…