Mocking Classes

Mocking a class rather than an interface might present some interesting obstacles. Perhaps you have ran into the dreaded:

You think nothing of it and happily add an expectation for toString. Then you get:

The reason is that EasyMock itself calls toString for each expectation, so it’s a never-ending story. However, it appears only when your class under test has overridden any (or all) of toString, equals or hashCode. There is a way around it. You can tell EasyMock’s MockClassControl which methods you want it to mock. Yes, you heard it right: “which methods you want it to mock”. I know, you’d rather want to tell it which methods you don’t want it to mock, like toString, equals and hashCode.

I’ll show you a couple of utility classes that let you do that. We ran into this problem in a previous project and wrote the classes below. They let you get away with this neat code that should be used whenever you mock a class:

Here are the classes:

Leave a Reply

Close Menu