如何在 Ruby 中进行测试
if shuffle
some_array.shuffle.each { |val| puts "#{val}" }
end
既然是 Ruby 方法,我是否需要测试 shuffle 或不需要?谢谢。
最佳答案
简短回答:否。
您可以相信 Ruby 会正确地做事。它有一个 huge number of tests已经。
长答案:是的。
您不应该直接测试 shuffle
方法,而应该测试您的代码是否产生了正确的结果。
由于您的代码使用了 puts
,因此测试起来非常烦人。如果您可以编写一个返回可以 打印的值的方法,那通常会好很多。编写代码时,请始终考虑如何测试它。
如果您正在为此苦苦挣扎,并且测试方法不明确,请先编写测试,然后编写代码使它们通过。
如果必须对您的值进行洗牌,那么您需要想出一种方法来确定它们是否已充分洗牌。这可能很困难,因为随机性是善变的。 shuffle
对您的数据不做任何事情的可能性很小但非零,这就是随机性的工作原理。当您的列表越小到可以保证仅对一个元素不执行任何操作的程度时,这种可能性就会显着增加。
因此,如果您可以描述为什么数据应该被打乱,以及什么构成了良好的打乱,那么您可以为此编写一个测试。
这是一个如何做到这一点的例子:
gem 'test-unit'
require 'test/unit'
class MyShuffler
def initialize(data)
@data = data
end
def processed
@data.map do |e|
e.downcase
end.shuffle
end
end
现在你可以这样使用了:
shuffler = MyShuffler.new(%w[ a b c d e f ])
# Thin presentation layer here where we're just displaying each
# element. Test code for this is not strictly necessary.
shuffler.processed.each do |e|
puts e
end
现在您为独立的数据操作编写测试代码,而不是表示部分:
gem 'test-unit'
require 'test/unit'
class MyShufflerTest < Test::Unit::TestCase
def test_processed
shuffler = MyShuffler.new(%w[ A B c Dee e f Gee ])
results = shuffler.processed
expected = %w[ a b c dee e f gee ]
assert_equal expected, results.sort
assert_not_equal expected, results
counts = Hash.new(0)
iterations = 100000
# Keep track of the number of times a particular element appears in
# the first entry of the array.
iterations.times do
counts[shuffler.processed[0]] += 1
end
expected_count = iterations / expected.length
# The count for any given element should be +/- 5% versus the expected
# count. The variance generally decreases with a larger number of
# iterations.
expected.each do |e|
assert (counts[e] - expected_count).abs < iterations * 0.05
end
end
end
关于ruby - 如何在 Ruby 中测试带随机播放的循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39353360/