代码之家  ›  专栏  ›  技术社区  ›  John F. Miller

在ruby中测试线程代码

  •  4
  • John F. Miller  · 技术社区  · 16 年前

    delayed_job 数据映射器的克隆。除了辅助进程中的线程之外,我已经得到了我认为可以工作和测试的代码。我期待着 延迟工作 了解如何测试这一点,但现在有针对这部分代码的测试。下面是我需要测试的代码。想法(我正在使用rspec(顺便说一句)

    def start
      say "*** Starting job worker #{@name}"
      t = Thread.new do
        loop do
          delay = Update.work_off(self) #this method well tested
          break if $exit
          sleep delay
          break if $exit
        end
        clear_locks
      end
    
      trap('TERM') { terminate_with t }
      trap('INT')  { terminate_with t }
    
      trap('USR1') do
        say "Wakeup Signal Caught"
        t.run
      end
    

    另见 this thread

    4 回复  |  直到 9 年前
        1
  •  3
  •   rud    16 年前

    您可以在测试时将辅助进程作为子进程启动,等待它完全启动,然后检查输出/向其发送信号。

    Unicorn 项目

        2
  •  9
  •   Automatico    11 年前

    Thread.new 方法,并确保任何“复杂”的东西都有自己的方法,可以单独测试。所以你会有这样的想法:

    class Foo
        def start
            Thread.new do
                do_something
            end
        end
        def do_something
            loop do
               foo.bar(bar.foo)
            end
        end
    end
    

    describe Foo
        it "starts thread running do_something" do
            f = Foo.new
            expect(Thread).to receive(:new).and_yield
            expect(f).to receive(:do_something)
            f.start
        end
        it "do_something loops with and calls foo.bar with bar.foo" do
            f = Foo.new
            expect(f).to receive(:loop).and_yield #for multiple yields: receive(:loop).and_yield.and_yield.and_yield... 
            expect(foo).to receive(:bar).with(bar.foo)
            f.do_something
        end
    end
    

    这样,你就不必花那么多时间来获得想要的结果。

        3
  •  0
  •   Jeff Waltzer    16 年前

    完全测试线程是不可能的。你能做的最好的事情就是使用mock。

    object.should_receive(:trap.),with('TERM')。和yield object.start

        4
  •  0
  •   michaeldpierce    11 年前

    Thread.stub(:new).and_yield
    start
    # assertions...
    
    推荐文章