rspec单元测试具有无限循环的方法

时间:2012-11-13 17:12:09

标签: unit-testing rspec

我有这样的方法

class SomeClass
  def self.test_method
    while(true)
      make_heavy_lifting
      sleep(60*60)
    end
  end
end

如何为此方法编写测试。

我想到的一个解决方案是存根睡眠方法,它工作但我无法存根while关键字。请建议单元测试具有无限循环的方法的最佳实践。

2 个答案:

答案 0 :(得分:6)

也许你可以将除了睡眠之外的所有内容移动到另一种方法,然后你只为该方法编写规范,我认为你真的不需要测试你的方法有一个while循环和睡眠(你不要我需要测试你的代码的每一行:P)但如果你想这样做,请检查这个问题,它有一些你可以尝试的东西What is the best practice when it comes to testing "infinite loops"?

答案 1 :(得分:1)

为了对此进行测试,我将html = (typeof(sd.someKey.s) != 'undefined') ?sd.someKey.s.a: '-'; 存根并使用它代替:loop

类:

while(true)

规格:

class SomeClass
  def self.test_method
    loop do
      make_heavy_lifting
      sleep(60*60)
    end
  end
end

这样它只会迭代一次。

编辑: 似乎在other question

中也提到了这一点
相关问题