使用打印到屏幕的参数对 Perl 函数进行单元测试 [英] Unit test a Perl function with parameters that print to a screen

查看:27
本文介绍了使用打印到屏幕的参数对 Perl 函数进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用打印到屏幕的参数对 perl 函数进行单元测试?

How can I unit test a perl function with a parameter that prints to a screen?

sub test {
  my $var = shift;
  if( $var eq "hello") {
    print "Hello";
  }
  else {
    print "World";
  }
} 

我想在打印到屏幕的函数中完全涵盖所有条件,但我不知道如何..

I want to fully cover all the conditions in a function that prints to a screen but I don't know how..

我在 stackoverflow 上看到了这个答案 如何对打印到屏幕的 Perl 函数进行单元测试?

I saw this answer at stackoverflow How can I unit test Perl functions that print to the screen?

是的,答案可以对输出字符串的函数进行单元测试,但前提是所需函数中没有参数..在我的情况下,我可以使用这个:

Yes the answer can unit test a function that outputs a string but only if there are no parameters in the function required.. in my case I can use this:

stdout_is(\&test, "World", 'test() return World');

但是我如何测试打印Hello";?

编辑

我尝试使用这个测试用例:

I tried using this test cases:

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");
}

由于函数的 stdout_is' 参数只是对函数的代码引用(如果我没记错的话),它没有 function(variables_here).

since stdout_is' parameter for the function is only a code reference to a function (if I'm not mistaken), it doesn't have the function(variables_here).

我还阅读了 perl Test::Output手动但我仍然找不到解决方案..还有其他方法还是我错过了什么?

I've also read the perl Test::Output manual but I still can't find a solution.. Are there any other ways or did I missed something?

所以我的主要问题是:如何对仅打印到屏幕(标准输出)的 perl 函数(带参数)进行单元测试?

推荐答案

你只需要将你想测试的调用包装在一个匿名子程序中

You just need to wrap the call you want to test in an anonymous subroutine

我使用 output_is 来测试 stdoutstderr.如果你有use warnings,这里的第四个测试应该会失败

I am using output_is to test both stdout and stderr. The fourth test here should fail if you have use warnings in place as you should

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');

这篇关于使用打印到屏幕的参数对 Perl 函数进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆