Robert Robert - 4 months ago 22
Perl Question

How to reuse mock objects in Perl unit tests?

I have a bunch of unit tests for my module, and I find that I copy the same mock and setup code from one to the other. How can I DRY that up and reuse the mock code?

I've placed this simple mock object next to my tests:

package MockObject;
1;


If I just say
use MockObject;
in the test case,
make test
cannot find MockObject. Makes sense; after all, it's not installed system wide and it's not next to the module under test.

I can run my tests with
prove -I lib -I t t/*.t
but I'd like to keep
make test
, if only for the laziness of typing a few characters less.

Since the mock object isn't a full module and shouldn't be officially installed anyway, I cannot and don't want to set
TEST_REQUIRES
in Makefile.PL.

Adding
test => { FILES => 't/*.t', INC => 't/' }
to Makefile.PL didn't help.

How can I (simply) reuse Perl mock code with the MakeMaker generated Makefile?

Answer

Setup PERL5LIB or add use lib in your script. I found FindBin package useful for setting up the lib path for tests. http://search.cpan.org/~nwclark/perl-5.8.7/lib/FindBin.pm

use FindBin qw($Bin);
use lib "$Bin/../lib";

where

$Bin - path to bin directory from where script was invoked

Comments