1

我想断言调用了一个特定的方法,但我不想模拟/存根该方法 - 我也想在测试中包含该代码。

例如,在 Ruby 中,类似:

def bar()
  #stuff I want to test
end

def foo()
  if condition
    bar()
  end

  #more stuff I want to test
end

# The test:

foo()
assert_called :bar

有没有人有建议(或更好的方法)?我的实际代码要复杂得多,所以请不要考虑示例的简单性。

4

2 回答 2

0

也许是这样的:

require 'set'

class Class
  def instrument
    self.instance_methods.each do |m|
      old = method(m)
      define_method(m) do |*a,&b|
        @__called__ ||= Set.new
        @__called__ << m
        old.bind(self).call(*a,&b)
      end
    end
  end
end

class Object
  def assert_called(method)
    if not (@__called__ && @__called__.include?(method))
      # You will have to figure out how to make this equivalent to a failing
      #   assertion for your favorite test framework
      raise "Assertion failed! #{method} has not been called"
    end
  end
end

然后在定义你的类之后,但在运行测试之前:

FooClass.instrument

请注意,我还没有测试过这段代码!

于 2012-02-17T21:15:17.693 回答
0

将其设置为两个测试用例确实是一种好方法,一个会调用foo()并检查是否bar()被调用,另一个会检查bar()它是否正常。当你在测试foo()时,你应该知道bar()应该返回什么。

于 2012-02-17T20:54:23.113 回答