我正在使用 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 被调用了两次呢?