gpt4 book ai didi

ruby - 提高ArgumentError ruby

转载 作者:行者123 更新时间:2023-12-03 09:03:00 24 4
gpt4 key购买 nike

我有一个简单的骰子类(class)。如何测试ArgumentError?

 class Die
def initialize(num)
if num < 1
raise(ArgumentError)
end
@num = num
end
def sides
return @sides
end

def roll
@value = rand(@num) + 1
return @value
end
end

这是我失败的尝试。
assert_raise ArgumentError do
zero = 0
die = Die.new(zero)
puts die.sides == raise(ArgumentError)
end

最佳答案

此实现应帮助您断言是否引发错误:

class TestDie < MiniTest::Unit::TestCase 
def test_argument_error
assert_raises ArgumentError do
Die.new(0)
end
end

def test_argument_error_not_raised
refute_raises ArgumentError do
Die.new(2)
end
end
end

要拒绝不应引发异常,可以编写类似于以下内容的自己的refute_raises方法:
def refute_raises
yield
rescue Exception => err
flunk "Expected no failures but #{mu_pp(err).chomp} was raised."
end

assert_raisesflunk的文档

关于ruby - 提高ArgumentError ruby ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22970627/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com