如何在最低测试中存入兰特? [英] How can I stub rand in minitest?
问题描述
我尝试了Random.stub :rand, 1 do ... end
和Kernel.stub :rand, 1 do ... end
和Class.stub :rand, 1 do ... end
(因为当我在运行rand(2)
的地方运行rand(2)
时,我得到了Class
).我也尝试过用Random.rand(2)
替换rand(2)
,但这没有帮助.
I've tried Random.stub :rand, 1 do ... end
and Kernel.stub :rand, 1 do ... end
and Class.stub :rand, 1 do ... end
(because when I run self.class
where I run rand(2)
I get Class
). I've also tried replacing rand(2)
with Random.rand(2)
but it doesn't help.
那我该如何对兰特进行存根处理?
So how do I stub out rand?
推荐答案
rand
是Kernel
模块的一部分,该模块混入每个类中.要对其进行存根处理,您需要在调用rand
的对象上调用stub
.
rand
is part of the Kernel
module that is mixed into every class. To stub it, you need to call stub
on the object where rand
is being called.
在一个示例中可能最容易看到.在下面的代码中,rand
是Coin
的私有实例方法,因为Coin
隐式继承自Object
和Kernel
.因此,我需要在Coin
的 instance 上存根.
It's probably easiest to see in an example. In the following code, rand
is a private instance method of the Coin
, because Coin
implicitly inherits from Object
and Kernel
. Therefore I need to stub on the instance of Coin
.
require "minitest/autorun"
require "minitest/mock"
class Coin
def flip
rand(0..1) == 1 ? "heads" : "tails"
end
end
class CoinTest < Minitest::Test
def test_flip
coin = Coin.new
coin.stub(:rand, 0) do
assert_equal("tails", coin.flip)
end
end
end
这篇关于如何在最低测试中存入兰特?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!