如何使用打印到屏幕的参数对perl函数进行单元测试?
sub test {
my $var = shift;
if( $var eq "hello") {
print "Hello";
}
else {
print "World";
}
}
Run Code Online (Sandbox Code Playgroud)
我想完全覆盖打印到屏幕的功能中的所有条件,但我不知道如何...
我在stackoverflow上看到了这个答案如何单元测试打印到屏幕的Perl函数?
是的答案可以单元测试一个输出字符串的函数,但只有在所需的函数中没有参数时...在我的情况下我可以使用:
stdout_is(\&test, "World", 'test() return World');
Run Code Online (Sandbox Code Playgroud)
但我怎么测试print "Hello";?
编辑
我尝试使用这个测试用例:
should_print_hello();
should_print_world();
sub should_print_world
{
stdout_is(\&test, "World", "should_print_world");
}
sub should_print_hello
{
# this does not work and outputs error
stdout_is(\&test("hello"), "Hello", "should_print_hello");
}
Run Code Online (Sandbox Code Playgroud)
因为stdout_is'函数的参数只是对函数的代码引用(如果我没有弄错),它没有function(variables_here).
我还阅读了perl Test :: Output手册,但我仍然无法找到解决方案..有没有其他方法或者我错过了什么?
所以我的主要问题是: 我如何单独测试只打印到屏幕(stdout)的perl函数(带参数)?
您只需要在匿名子例程中包装要测试的调用
我output_is用来测试两者stdout和stderr.如果您有应有use warnings的地方,那么第四次测试应该会失败
output_is(sub { test('hello') }, 'Hello', '', 'Test specific output');
output_is(sub { test('xxx') }, 'World', '', 'Test non-specific output');
output_is(sub { test('') }, 'World', '', 'Test null string parameter output');
output_is(sub { test() }, 'World', '', 'Test no-parameter output');
Run Code Online (Sandbox Code Playgroud)