的最佳实践是什么

的最佳实践是什么

本文介绍了测试“无限循环"的最佳实践是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的基本逻辑是在某处运行一个无限循环并尽可能地对其进行测试.使用无限循环的原因并不重要(游戏的主循环、类似守护进程的逻辑......)而且我更多地询问有关这种情况的最佳实践.

My basic logic is to have an infinite loop running somewhere and test it as best as possible. The reason for having an infinite loop is not important (main loop for games, daemon-like logic...) and I'm more asking about best practices regarding a situation like that.

我们以这段代码为例:

module Blah
  extend self

  def run
     some_initializer_method
     loop do
        some_other_method
        yet_another_method
     end
  end
end

我想使用 Rspec 测试方法 Blah.run(我也使用 RR,但简单的 rspec 将是一个可以接受的答案).

I want to test the method Blah.run using Rspec (also I use RR, but plain rspec would be an acceptable answer).

我认为最好的方法是再分解一点,比如将循环分成另一种方法或其他方法:

I figure the best way to do it would be to decompose a bit more, like separating the loop into another method or something:

module Blah
  extend self

  def run
     some_initializer_method
     do_some_looping
  end

 def do_some_looping
   loop do
     some_other_method
     yet_another_method
   end
 end
end

...这允许我们测试 run 并模拟循环...但在某些时候需要测试循环内的代码.

... this allows us to test run and mock the loop... but at some point the code inside the loop needs to be tested.

遇到这种情况,你会怎么做?

So what would you do in such a situation?

简单地不测试这个逻辑,意味着测试some_other_method &yet_another_method 但不是 do_some_looping 吗?

Simply not testing this logic, meaning test some_other_method & yet_another_method but not do_some_looping ?

循环在某个时候通过模拟中断了吗?

Have the loop break at some point via a mock?

……还有什么?

推荐答案

更实际的做法是在单独的线程中执行循环,断言一切正常,然后在不再需要时终止线程.

What might be more practical is to execute the loop in a separate thread, assert that everything is working correctly, and then terminate the thread when it is no longer required.

thread = Thread.new do
  Blah.run
end

assert_equal 0, Blah.foo

thread.kill

这篇关于测试“无限循环"的最佳实践是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 03:47