Mocha 最多期望一次,调用两次,但是方法显然只调用一次

Posted

技术标签:

【中文标题】Mocha 最多期望一次,调用两次,但是方法显然只调用一次【英文标题】:Mocha expected at most once, invoked twice, but method is clearly invoked only once 【发布时间】:2013-05-01 23:29:21 【问题描述】:

我正在使用 Mocha 进行模拟测试。下面是相关代码:

# test_player.rb
should "not download the ppg more than once for a given year" do
  @durant.expects(:fetch_points_per_game).at_most_once
  ppg = @durant.points_per_game
  ppg2= @durant.points_per_game
  assert_equal ppg, ppg2, "A player should have a points per game"
end

# player.rb
class Player
  # ...

  def points_per_game(year=Date.today.year)
    @points_per_game ||= fetch_points_per_game(year)
  end
  alias_method :ppg, :points_per_game

  private

  def fetch_points_per_game(year=Date.today.year)
    31.2
  end
end

测试失败,抱怨“意外调用:#.fetch_points_per_game(any_parameters)”

我对我的代码的理解是,如果@point_per_game 为nil,则将调用fetch_points_per_game,否则,结果将被缓存以供将来调用points_per_game。那么为什么测试会抱怨 fetch_points_per_game 被调用了两次呢?

【问题讨论】:

【参考方案1】:

在您的预期中,您没有指定返回值,因此存根调用返回 nil。这就是为什么它被第二次调用。如果您将期望更改为:

@durant.expects(:fetch_points_per_game).at_most_once.returns(1.23)

您应该会发现测试现在通过了。

【讨论】:

以上是关于Mocha 最多期望一次,调用两次,但是方法显然只调用一次的主要内容,如果未能解决你的问题,请参考以下文章