Search code examples
perltestingperl-module

How do I test my module that uses File::ShareDir?


I am writing a module that installs a shared file in the dist directory using File::ShareDir::Install. Inside the main exported function in the module, the file is then located using File::ShareDir.

This function loads the shared file, and looks up a string in the file. In one of my tests, I wanted to check if the function returned the correct values for a few inputs. So, the test looks like:

my @cases = (
    [ 'input1' => 'expected1' ],
    # etc
);

for my $case ( @cases ) {
    my ($input, $expected) = @$case;
    is(
        my_lookup_function($input),
        $expected,
        "$input => $expected",
    );
}

However, the test does not run because

my $dir = dist_dir('My-Dist');

croaks.

My Makefile.PL seems to be correct, because I can find the share file under blib. I just do not know what I need to do to get the File::ShareDir::dist_dir call in my module to find this directory during testing.

I did look at Test::File::ShareDir, but I don't understand if it can be used to do what I am trying to do.

I would appreciate it if you can either tell me how to achieve desired behavior with the current setup, or suggest ways of doing things differently (and presumably correctly ;-)


Solution

  • Works for me.

    perl Makefile.PL ; make
    make test
    prove -b
    

    $ tree
    .
    ├── Makefile.PL
    ├── share
    │   └── quux
    └── t
        └── foo.t
    
    2 directories, 3 files
    
    $ cat Makefile.PL
    use ExtUtils::MakeMaker;
    use File::ShareDir::Install;
    
    install_share 'share';
    WriteMakefile;
    
    package MY;
    use File::ShareDir::Install qw(postamble);
    
    
    $ cat t/foo.t
    use File::ShareDir qw(dist_dir);
    use Test::More;
    
    diag dist_dir('My-Dist');
    
    pass;
    done_testing;