当被测试者在 Perl 中使用 TAP 失败退出时,是否可以测试预期的错误?
假设您正在运行一些单元测试,并且您想查看正在测试的方法(或脚本或函数或其他内容)是否失败。如何设置这样的测试?我希望有这样的事情:
ok( $obj->method($my, $bad, $params) == DEATH, 'method dies as expected');
虽然我不知道它是如何工作的,因为当传递错误的参数并且测试脚本停止时,方法会死掉。
还有别的办法吗?
Suppose you're running some unit tests and you want to see if the method ( or script or function or whatever) you're testing fails as it should. How do you setup such a test? I'm hoping for something like this:
ok( $obj->method($my, $bad, $params) == DEATH, 'method dies as expected');
although I don't see how it would work since method
die
s when passed bad parameters and the test script stops.
Is there another way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您是否尝试过 Test::Exception ?
dies_ok
应该做你想做的。例如:Have you tried Test::Exception?
dies_ok
should do what you want. Eg:我推荐 Test::Fatal 而不是 Test::Exception。
Test::Exception 已经存在很长时间了,因此很多现有的测试套件都使用它,但 Test::Fatal 更容易学习。 Test::Fatal 仅导出 1 个函数:
异常
。这会运行关联的代码并返回它引发的异常,如果运行没有错误则返回 undef。然后,您可以使用任何正常的 Test::More 函数测试该返回值,例如is
、isnt
、like
或isa_ok
。Test::Exception 要求您学习它自己的测试函数,例如
throws_ok
和dies_ok
,并记住不要在代码和测试名称之间放置逗号。所以,你的例子是:
或者你可以使用
like
来匹配预期的错误消息,或者使用isa_ok
来测试它是否抛出了正确的异常对象类。与 Test::Exception 相比,Test::Fatal 只是为您提供了更大的灵活性和更少的学习曲线。
I recommend Test::Fatal rather than Test::Exception.
Test::Exception has been around for a long time, so a lot of existing test suites use it, but Test::Fatal is easier to learn. Test::Fatal exports only 1 function:
exception
. This runs the associated code and returns the exception that it threw, orundef
if it ran without error. You then test that return value using any of the normal Test::More functions likeis
,isnt
,like
, orisa_ok
.Test::Exception requires you to learn its own testing functions like
throws_ok
anddies_ok
, and remember that you don't put a comma between the code and the test name.So, your example would be:
Or you could use
like
to match the expected error message, orisa_ok
to test if it threw the correct class of exception object.Test::Fatal just gives you more flexibility with less learning curve than Test::Exception.
实际上没有必要使用模块来做到这一点。您可以将预计失败的调用包装在
eval
块中,如下所示:如果
eval
中一切顺利,它将返回最后执行的语句,即在本例中为1
。如果失败,eval
将返回undef
。这与ok
想要的相反,因此!
翻转值。如果需要,您可以按照该行检查实际的异常消息:
There's really no need to use a module to do this. You can just wrap the call that you expect to fail in an
eval
block like so:If all goes well in the
eval
, it will return the last statement executed, which is1
in this case. if it fails,eval
will returnundef
. This is the opposite of whatok
wants, so!
to flip the values.You can then follow that line with a check of the actual exception message if you want: