如何在最低测试中存入兰特? [英] How can I stub rand in minitest?

查看:72
本文介绍了如何在最低测试中存入兰特?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了Random.stub :rand, 1 do ... endKernel.stub :rand, 1 do ... endClass.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?

推荐答案

randKernel模块的一部分,该模块混入每个类中.要对其进行存根处理,您需要在调用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.

在一个示例中可能最容易看到.在下面的代码中,randCoin的私有实例方法,因为Coin隐式继承自ObjectKernel.因此,我需要在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆