ruby - Mocha 预计最多一次,调用两次,但方法显然只调用一次

标签 ruby testing mocking expectations ruby-mocha

我正在使用 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 为零,将调用 fetch_points_per_game,否则,将缓存结果以供将来调用 points_per_game。那么为什么测试会提示 fetch_points_per_game 被调用了两次?

最佳答案

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

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

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

关于ruby - Mocha 预计最多一次,调用两次,但方法显然只调用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16328054/

相关文章:

testing - Cypress 测试因我的应用程序未捕获的异常而失败 - support/index.js 不起作用

angular - 如何使用 karma 在 Angular 中对异步 ngIf 进行单元测试

c# - 最小起订量无效方法

ruby-on-rails - Gemfile :22: syntax error, 意外的 tIDENTIFIER,预计输入结束

ruby-on-rails - 如何检查表中是否存在列?

ruby-on-rails - ActionView::Template::Error(无法打开到本地主机的 TCP 连接:9292(连接被拒绝 - 连接(2)用于 "localhost"端口 9292))

javascript - 在 AngularJS Controller 规范中测试来自服务的回调

ruby - 查找以 "j"开头并包含 "w"的 4 个字母字符串的所有排列?

angular - 测试广播服务

python - 如何在python中模拟链式函数调用?