my $smtp = Net::SMTP->new($mailhost); ... if ($i_dont_want_to_send_mail) { package Mock::SMTP; our @ISA = qw(Net::SMTP); no strict qw(refs); for (qw(mail to data dataend quit)) { *$_ = sub { }; } for (qw(datasend)) { *$_ = sub { shift; print @_, "\n" } } # re-bless my Net::SMTP reference to a Mock reference $smtp = bless $smtp || {}; }
Thursday, July 22, 2010
simple overrides for quick mocking in perl
A more concrete example (and one I use too frequently) of overriding for testing similar to what is described by Sawyer X at blogs.perl.org: Simple symbol overriding for tests. Of course, my example uses inheritance and re-blessing rather than symbol overriding, but the result is basically the same. I like to use the snippet below to test mail sending functionality by simply printing the resulting mail to stdout.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment