Ruby 的 Test::Unit
有 assert_nothing_raised
。 Test::Unit
已替换为 MiniTest .为什么 MiniTest 的断言/期望与此没有任何相似之处?例如,您可以期望 must_raise
而不是 wont_raise
。
最佳答案
MiniTest 确实在它的 Test::Unit 兼容层中实现了 assert_nothing_raised
,但是在它自己的测试中(MiniTest::Unit
和 MiniTest::Spec
) 它不实现任何这样的测试。原因是,程序员争辩说,测试什么都不提出不是测试任何东西;您从不期望在测试中引发任何事情,除非您正在测试异常。如果测试代码中出现意外(未捕获)的异常,您将收到测试按顺序报告的异常,您就会知道自己遇到了问题。
例子:
require 'minitest/autorun'
describe "something" do
it "does something" do
Ooops
end
end
输出:
Run options: --seed 41521
# Running tests:
E
Finished tests in 0.000729s, 1371.7421 tests/s, 0.0000 assertions/s.
1) Error:
test_0001_does_something(something):
NameError: uninitialized constant Ooops
untitled:5:in `block (2 levels) in <main>'
1 tests, 0 assertions, 0 failures, 1 errors, 0 skips
这正是您想知道的。如果您不希望筹集到任何资金,那么您就没有得到它,而且您已被告知。
所以,这里的论点是:不要使用assert_nothing_raised
!这只是一个毫无意义的拐杖。参见,例如:
https://github.com/seattlerb/minitest/issues/70
https://github.com/seattlerb/minitest/issues/159
http://blog.zenspider.com/blog/2012/01/assert_nothing_tested.html
另一方面,显然 assert_nothing_raiseed
符合用户的一些直觉,因为很多人期望 wont_raise
与 must_raise
一起,等等。特别是人们希望将断言 集中于此,而不仅仅是测试。幸运的是,MiniTest 极其简约和灵活,所以如果您想添加自己的例程,您可以。因此,您可以编写一个方法来测试无异常并在无异常时返回已知结果,现在您可以断言该已知结果。
例如(我并不是说这很完美,只是展示了这个想法):
class TestMyRequire < MiniTest::Spec
def testForError # pass me a block and I'll tell you if it raised
yield
"ok"
rescue
$!
end
it "blends" do
testForError do
something_or_other
end.must_equal "ok"
end
end
关键不在于这是好主意还是坏主意,而是 MiniTest 从来没有责任为您做这件事。
关于ruby - 为什么 MiniTest::Spec 没有 wont_raise 断言?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12499259/