【问题标题】:Better way to test if method is called x times with MiniTest?用 MiniTest 测试方法是否被调用 x 次的更好方法?
【发布时间】:2015-01-10 09:43:00
【问题描述】:

今天我从一些基本的 minitest 实现开始,终于找到了一种方法来测试一个类上的方法是否被调用了两次。

在 RSpec 中我会这样做:

expect(@foo).to receive(:some_heavy_calculation).once
2.times { @foo.bar }

现在,我为 MiniTest 提出了以下实现,但我不确定这是否是实现它的方法,因为 this.这就是我所拥有的

require 'minitest/autorun'

class Foo
  def bar
    @cached_value ||= some_heavy_calculation
  end

  def some_heavy_calculation
    "result"
  end
end

class FooTest < Minitest::Test
  def setup
    @foo = Foo.new
  end

  def cache_the_value_when_calling_bar_twice
    mock = Minitest::Mock.new
    mock.expect(:some_heavy_calculation, [])
    @foo.stub :some_heavy_calculation, -> { mock.some_heavy_calculation } do
      2.times { assert_equal_set @foo.bar, [] }
    end
    mock.verify
  end
end

我真的必须用一个模拟来实现这一点,这将是必须调用 x 次的方法上的主题存根的结果?

【问题讨论】:

    标签: ruby testing mocking minitest


    【解决方案1】:

    我不得不做类似的事情。这就是我最终的结果......

    def cache_the_value_when_calling_bar_twice
      count = 0
      @foo.stub :some_heavy_calculation, -> { count += 1 } do
        2.times { assert_equal_set @foo.bar, [] }
      end
      assert_equal 1, count
    end
    

    【讨论】:

      【解决方案2】:

      我在其中一个测试中做了类似的事情。如果您的方法可能调用一个类的多个实例,这也适用:

      test "verify number of method calls" do
       count = 0
       Foo.stub_any_instance(:some_heavy_calculation, -> { count += 1 }) do
        2.times { assert_equal_set @foo.bar, [] }
       end
       assert_equal 1, count
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-03
        • 2018-08-31
        相关资源
        最近更新 更多