我怎样才能在 minitest 中存根兰特?
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
(因为当我 运行 self.class
我 运行 rand(2)
我得到 Class
)。我也试过用 Random.rand(2)
替换 rand(2)
但它没有帮助。
那么我该如何存根呢?
rand
是混合到每个 class 中的 Kernel
模块的一部分。要存根,您需要在调用 rand
的对象上调用 stub
。
在示例中可能最容易看出。在下面的代码中,rand
是Coin
的私有实例方法,因为Coin
隐式继承自Object
和Kernel
。因此,我需要在 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
我已经尝试了 Random.stub :rand, 1 do ... end
和 Kernel.stub :rand, 1 do ... end
以及 Class.stub :rand, 1 do ... end
(因为当我 运行 self.class
我 运行 rand(2)
我得到 Class
)。我也试过用 Random.rand(2)
替换 rand(2)
但它没有帮助。
那么我该如何存根呢?
rand
是混合到每个 class 中的 Kernel
模块的一部分。要存根,您需要在调用 rand
的对象上调用 stub
。
在示例中可能最容易看出。在下面的代码中,rand
是Coin
的私有实例方法,因为Coin
隐式继承自Object
和Kernel
。因此,我需要在 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