3

我编写了这段代码,并尝试使用 minitest 对其进行测试,但似乎我没有使用正确的语法来处理异常:/

def my_method(a,b=10)
  begin
    a/b
  rescue
    raise 'bla'
  end
end

describe 'my test' do
  it "must divide" do
    my_method(6,3).must_equal(2)
  end

  it "can't divide by zero and raise bla" do
    my_method(6,0).must_raise 'bla'
  end

  it "must divide by 10 if there is only one arg" do
    my_method(10).must_equal(1)
  end
end

输出 :

运行选项:--seed 30510

运行测试:

..E

在 0.001000 秒、3000.0000 次测试/秒、2000.0000 次断言/秒内完成测试。

1) 错误:test_0002_can_t_divide_by_zero_and_raise_bla(我的测试):RuntimeError: bla essai.rb:9:in my_method' essai.rb:19:intest_0002_can_t_divide_by_zero_and_raise_bla'

3 次测试,2 次断言,0 次失败,1 次错误,0 次跳过

第二个测试给我一个错误,有人可以帮助我吗?

4

1 回答 1

8

您应该调用must_raiseproc,而不是方法调用结果:

require 'minitest/autorun'

def my_method(a,b=10)
  begin
    a/b
  rescue
    raise 'bla'
  end
end

describe 'my test' do
  it "must divide" do
    my_method(6,3).must_equal(2)
  end

  it "can't divide by zero and raise bla" do
    div_by_zero = lambda { my_method(6,0) }
    div_by_zero.must_raise RuntimeError
    error = div_by_zero.call rescue $!
    error.message.must_equal 'bla'
  end

  it "must divide by 10 if there is only one arg" do
    my_method(10).must_equal(1)
  end
end
于 2011-12-28T10:11:45.103 回答