【问题标题】:rspec unit testing a method which has a infinite looprspec 单元测试具有无限循环的方法
【发布时间】:2012-11-02 03:42:54
【问题描述】:

我有这样的方法

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

我如何为此方法编写测试。

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

【问题讨论】:

    标签: unit-testing rspec


    【解决方案1】:

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

    【讨论】:

    • 同意。但我希望有什么方法可以存根 while(true) 关键字。如果不是,那么我必须将逻辑从中分离出来。
    【解决方案2】:

    为了测试这个,我存根 :loop 并使用它而不是 while(true)

    类:

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

    规格:

    describe SomeClass do
      describe '#test_method' do
        expect(SomeClass).to receive(:loop).and_yield
        expect(SomeClass).to receive(:make_heavy_lifting)
        expect(SomeClass).to receive(:sleep).with(60*60)
    end
    

    这样它只会遍历一次。

    编辑: 似乎other question

    中也建议了这一点

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-17
      • 1970-01-01
      • 1970-01-01
      • 2011-08-22
      • 2019-02-03
      • 2019-02-03
      • 2020-07-23
      • 1970-01-01
      相关资源
      最近更新 更多