2

I'm writing unit tests using Test::More and Test::Output. I use Test::More to validate the return values and I plan to use Test::Output to validate the stdout produced by my subroutines.

I am attempting to write test cases for a subroutine whose stdout is dependent on the arguments sent. Test::Output::stdout_like(code reference, regexp, test description) looks to have the functionality I want, however I am struggling to construct a code reference which contains an argument.

I presume this is a common practice within Perl unit testing scripts. Can anyone offer an example?

Side note, thanks to Kurt W. Leucht for his Perl unit testing introduction: Perl build, unit testing, code coverage: A complete working example

Community
  • 1
  • 1
jgrump2012
  • 397
  • 3
  • 11

1 Answers1

2

No you can't directly include an arg within a coderef.

To pass an arg to a coderef you need to actually call it:

mysub( $arg );      # the usual way to call the sub
$coderef = \&mysub; # get the reference to the sub
$coderef->( $arg ); # call the coderef with an arg (or &$coderef($arg))

But to get something working with Test::Output you can wrap calls to the subroutines you want to test in an another subroutine:

use Test::Output;
sub callmysubwitharg { mysub($arg) }
stdout_like \&callmysubwitharg, qr/$expecting/, 'description';

And, this is doing the same thing using an anonymous subroutine:

stdout_like { mysub($arg) } qr/$expecting/, 'description';
stevenl
  • 6,736
  • 26
  • 33