【问题标题】:Continue assertion after failures in rubyruby 失败后继续断言
【发布时间】:2014-05-08 14:12:10
【问题描述】:

我的断言示例如下,

class test < Test::Unit::TestCase
     def test_users
      begin
       assert_equal(user.name, 'John')
       assert_equal(user.age, 30)
       assert_equal(user.zipcode, 500002)  
      rescue Exception
       raise
      end 

     end   
   end

如果任何一个断言失败,我应该继续处理下一个断言并收集失败断言并在结果结束时显示失败。

我使用了 add_failure 方法,它适用于循环条件

rescue Test::Unit::AssertionFailedError => e
          add_failure(e.message, e.backtrace)

有人可以帮忙吗?

【问题讨论】:

  • 如果您将每个断言作为自己的测试,您将有效地获得您想要的行为
  • 救援在您的示例中提供了什么价值?
  • 我的救援看起来像这样救援异常引发结束

标签: ruby-on-rails ruby assertions testunit


【解决方案1】:

一个好的单元测试应该准确地测试一件事,特别是为了避免像你刚刚遇到的问题。此测试用例将报告所有个失败的测试,而不仅仅是第一个失败的测试:

class MyTest < Test::Unit::TestCase
  def test_user_name
    assert_equal(user.name, 'John')
  end

  def test_user_age 
    assert_equal(user.age, 30)
  end

  def test_user_zipcode
    assert_equal(user.zipcode, 500002)  
  end 
end   

【讨论】:

  • 我和其他人为每个方法调用编写一个测试,而不是每个断言:stackoverflow.com/questions/762512/… 所以 karan 的问题似乎是合理的,尽管我不想做他问自己的事情。
  • @DaveSchweisguth - 我在一个测试用例中放置一些断言没有问题,但是为了得到你可以得到的结果而修补和破坏库似乎很奇怪遵循其准则。当你知道一个测试失败时,在一个测试中进行多个断言 - 你不关心其余的。
  • @UriAgassi 当我在一种方法中有多个断言时,是否可以在最后显示断言失败。
  • 断言的全部意义在于它们未通过 whole 测试。测试suite 向您显示所有test case 失败,这正是您想要的。你当然可以修补代码来实现这一点,但这就像打破一个非常好的玩具......
【解决方案2】:

您的主要问题是 assert_equal 最终会调用 assert(如下所示)并且 assert 会引发 ArgumentException。

文件 test/unit/assertions.rb,第 144 行

def assert_equal(exp, act, msg = nil)
  msg = message(msg) {
  # omitted code to save space
 } 
  assert(exp == act, msg)
end

文件 test/unit/assertions.rb,第 29 行

def assert(test, msg = UNASSIGNED)
  case msg
  when UNASSIGNED
    msg = nil
  when String, Proc
  else
    bt = caller.reject { |s| s.rindex(MINI_DIR, 0) }
    raise ArgumentError, "assertion message must be String or Proc, but #{msg.class} was given.", bt
  end
  super
end

您可以扩展 Test::Unit::Assertions 并提供一个不会引发 ArgumentError 的断言,这是在失败的断言之后停止继续的原因。

请参阅this 问题以获取有关朝着该方向发展并添加安全断言的建议。

【讨论】:

    【解决方案3】:

    请在 Ruby 中查找失败后继续断言的代码:

    def raise_and_rescue  
      begin  
        puts 'I am before the raise.'  
        raise 'An error has occured.'  
        puts 'I am after the raise.'  
      rescue  
        puts 'I am rescued.'  
      end  
      puts 'I am after the begin block.'  
    end  
    

    输出:

    红宝石 p045handexcp.rb
    我在加薪之前。
    我得救了。
    我在开始块之后。
    退出代码:0

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-08
      • 2010-12-15
      • 1970-01-01
      • 2015-12-18
      • 1970-01-01
      • 2013-07-29
      • 1970-01-01
      • 2011-10-13
      相关资源
      最近更新 更多