gpt4 book ai didi

ruby - 测试这个的最佳方法是什么?

转载 作者:数据小太阳 更新时间:2023-10-29 06:35:57 26 4
gpt4 key购买 nike

我正在研究 EdgeCase Ruby Koans。在 about_dice_project.rb ,有一个名为“test_dice_values_should_change_between_rolls”的测试,很简单:

  def test_dice_values_should_change_between_rolls
dice = DiceSet.new

dice.roll(5)
first_time = dice.values

dice.roll(5)
second_time = dice.values

assert_not_equal first_time, second_time,
"Two rolls should not be equal"
end

除了出现在那里的这条评论:

# THINK ABOUT IT:
#
# If the rolls are random, then it is possible (although not
# likely) that two consecutive rolls are equal. What would be a
# better way to test this.

这(显然)让我开始思考:可靠地(具体地和一般地)随机测试某些东西的最佳方法是什么?

最佳答案

恕我直言,到目前为止,大多数答案都错过了 Koan 问题的要点,@Super_Dummy 除外。让我详细说明一下我的想法......

假设我们不是掷骰子,而是掷硬币。再加上在我们的集合中只使用一个硬币的另一个约束,我们就有了一个可以生成“随机”结果的最小非平凡集合。

如果我们想检查每次翻转“硬币组”[在本例中为一枚硬币]是否产生不同的结果,我们希望每个单独结果的相同50% 的时间,在统计的基础上。通过 n 次迭代运行 that 单元测试对于一些大的 n 将简单地运行 PRNG。它没有告诉您关于两个结果之间实际相等或不同的任何实质内容。

换句话说,在这个 Koan 中,我们实际上并不关心每次掷骰子的值。我们真的更关心返回的卷实际上是不同卷的表示。检查返回值是否不同只是一级检查。

大多数时候这就足够了——但在极少数情况下,随机性可能会导致单元测试失败。这不是一件好事™。

如果在连续两次掷骰返回相同结果的情况下,我们应该检查这两个结果是否实际上由不同的对象表示。这将使我们能够在将来 [如果需要的话] 重构代码,同时确信测试仍然总是捕获任何行为不正确的代码。

长话短说;博士?

def test_dice_values_should_change_between_rolls
dice = DiceSet.new

dice.roll(5)
first_time = dice.values

dice.roll(5)
second_time = dice.values

assert_not_equal [first_time, first_time.object_id],
[second_time, second_time.object_id], "Two rolls should not be equal"

# THINK ABOUT IT:
#
# If the rolls are random, then it is possible (although not
# likely) that two consecutive rolls are equal. What would be a
# better way to test this.
end

关于ruby - 测试这个的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2082970/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com