问题描述
我的基本逻辑是在某个地方运行无限循环并对其进行尽可能的最佳测试.产生无限循环的原因并不重要(游戏的主循环,类似守护程序的逻辑...),而我更多的是询问有关此类情况的最佳实践.
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.
让我们以下面的代码为例:
Let's take this code for example:
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
这篇关于关于测试“无限循环"的最佳实践是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!