Cold Hard Code

November 2009 Archives

How to test custom Moose types.

By J. Shirley on November 30, 2009 4:29 PM |
Comments welcome

I recently had a task where I could either trust my brilliant and prodigious programming skills, or I could write a unit test.

It was really quite easy, and I'm very happy with how easy MooseX::Types makes this.

First, you have to have your types defined, something like this:

Very simple, it just validates the date is after today. Nothing magic. Now, to write a unit test, you have to be able to check this assertion. This is made very easy because MooseX::Types provides an exportable "is_$type" method. However, that doesn't make for easy unit test construction.

Behold, my recipe:

A few things to note that are important:

  • This loudly complains about unimplemented tests
  • This uses some idiomatic Perl, mostly in terms of $code_ref->() — Don't be scared of that.
  • __PACKAGE__->>can("foo") returns an executable code reference, and this recipe shows why that's so useful.

Enjoy.

Comments welcome