In my module Foo.pm I got some anonymous functions, e.g.
our $anon = sub {
my $parameter = shift;
return $parameter * $parameter;
}
I'm using Test::More
to write unit tests for the functions in my module.
For normal subroutines, i can use can_ok("Foo.pm", @subs)
with @subs
containing the subroutine names. For anonymous functions, I get the following error:
Foo->can('$anon') failed
Is there any way to dereference the functions and pass them to can_ok()
?
CodePudding user response:
can
works by looking at inheritance and module composition to determine if a thing can execute a method. If you have package variables that contain code refs, you cannot use that sort of test. It makes no sense.
You could test whether your $anon
gets exported correctly. In your example above you are using it without the package name, so I am assuming you are exporting it. But keep in mind that Exporter suggests not to export variables.
Instead, I would suggest checking if there is a symbol in the package, and that it's of the right type.
isa_ok $Foo::anon, 'CODE';
That test will fail if that symbol doesn't exist, or isn't a code reference.
To do that with a list of sub names, you can use interpolation, but you have to disable strict refs
.
package Foo;
our $one = sub { 1 };
our $two = sub { 2 };
package main;
use strict;
use warnings;
use Test::More;
for my $sub (qw/ one two three/) {
no strict 'refs';
isa_ok ${ "Foo::$sub" }, 'CODE';
}
done_testing;
If you want anonymous methods you should probably just follow convention and name them with an underscore, such as sub _anon
.