【问题标题】:Testing infinite loop with MiniTest and using mocking使用 MiniTest 测试无限循环并使用模拟
【发布时间】:2015-05-06 01:22:50
【问题描述】:

我的代码中有一个部分轮询队列中的消息,然后根据消息类型对其进行操作:

@queue = Foo::Queue.new
loop do
  @queue.poll do |message|                                                                                                                              
    if message[:task] == TAKEACTION
      result = takeaction(message)
      @queue.send_result(result, message)
    end
    @queue.pong(message) if message[:task] == PING
  end
end

如何设置测试以提供单个 message 并验证 @queue 是否按我预期的方式对其进行操作?

我很少看到关于在 minitest 中测试块的内容,并且在 ruby​​ 中没有发现任何关于打破无限循环的内容,尽管我在 python 中发现了一个想法,您可以在其中设置第二次运行以引发异常。

任何 ruby​​ / minitest 大师可以提供帮助吗?

【问题讨论】:

标签: ruby tdd minitest


【解决方案1】:

对于 minitest,使用存根就可以了。下面的示例是独立的,可以独立运行。您可以将异常作为带有存根的 lambda 发送,以打破无限循环并继续测试。

# class receiving the messages from class being tested
class Obj
  def method_if_true
    # do some stuff
    return 'anything that is true'
  end

  def method_if_false
    # do some stuff
    false
  end
end

# class to be tested
class TestingLoop
  def initialize(args)
    @obj = args.fetch(:object, Obj.new)
    @bool = args[:bool]
  end

  def looping
    loop do
      if @bool
        @obj.method_if_true
        # @bool is true
      elsif !@bool
        @obj.method_if_false
        # @bool is false
      end
    end
  end
end

require 'minitest/autorun'
# class that tests
class TestTestingLoop < MiniTest::Test
  def setup
    @obj = Obj.new
    @raises_exception = lambda { raise RuntimeError.new }
    # could use the '->' syntax instead of the word lambda
  end

  def test_sends_correct_method_when_true
    @obj.stub :method_if_true, @raises_exception do
      testing_loop = TestingLoop.new({object: @obj, bool: true})
      assert_raises(RuntimeError) { testing_loop.looping }
    end
  end

  def test_sends_correct_method_when_false
    @obj.stub :method_if_false, @raises_exception do
      testing_loop = TestingLoop.new({object: @obj, bool: false})
      assert_raises(RuntimeError) { testing_loop.looping }
    end
  end
end

【讨论】:

    猜你喜欢
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 2012-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多