Mocking Parts of Objects

chromatic on 2004-03-13T05:45:52

The more I use Test::MockObject, the more I discover that I only need to mock small pieces of well-designed objects.

This came to a head today when I made the template() method of Jellybean::Response a little smarter. Instead of making repeated method calls to set individual pieces of template data, you can now pass a hash reference containing multiple pieces of data. That's less code! You can also request the whole template data in one chunk, too, but that's a separate issue.

My tests use a mock object to test that containers set template data correctly in the response object. After I improved template(), I converted one container to the new format. Suddenly, four tests failed. Since I'd mocked a template() method, the test code no longer matched the capabilities of the object it mocked.

Clearly, there was room in the world for Test::MockObject::Extends. So I wrote 52 lines of code (with liberal spacing and brace placement) and 44 lines of tests. More importantly, it required adding one line to the Jellybean test, changing another line, and deleting the not-so-accurate mocked template() implementation. Presto, all tests pass again.

I seem to promise to add documentation and post the code quite a bit lately, so replay the last few messages.

Oh yeah, dissatisfaction with the state of the world is great when it motivates me to improve things that need improving, but I originally set out today to add two small features to my article managing program. Of course, that lead me to make the templating simpler there, which lead to me refactoring and adding one nifty new feature to the Jellybean templating system.... So that's why I rarely finish anything. I'm too productive.


this sounds nifty!

lachoy on 2004-03-14T14:15:40

I'll be taking advantage of it right quick.

BTW, I gave a presentation to the Pittsburgh Perl Mongers last week about mock objects. Just for your library... (and any improvements welcome!)

Re:this sounds nifty!

chromatic on 2004-03-15T06:11:20

Nice presentation!

I'm toying with another approach to making T::MO::E work well, so it could be a couple of days. I'll likely release new versions of Mail::Action, Mail::SimpleList, and Mail::TempAddress first, however. That might be as early as tomorrow.

You'll enjoy this

Aristotle on 2004-07-03T14:28:45

I know I'm a bit late to this entry, but I think you want to learn about "yak shaving".