类 Object
Object
为 Minitest::Mock
提供的扩展。
公共实例方法
stub(name, val_or_callable, *block_args, **block_kwargs, &block) 点击切换源代码
添加一个临时的桩方法,在 block
的持续时间内替换 name
。如果 val_or_callable
响应 call,则返回调用它的结果,否则按原样返回值。如果桩方法产生一个块,则会传递 block_args
。在 block
结束时清理桩。方法 name
必须在桩之前存在。
def test_stale_eh obj_under_test = Something.new refute obj_under_test.stale? Time.stub :now, Time.at(0) do assert obj_under_test.stale? end end
调用超类方法
# File minitest-5.25.4/lib/minitest/mock.rb, line 298 def stub name, val_or_callable, *block_args, **block_kwargs, &block new_name = "__minitest_stub__#{name}" metaclass = class << self; self; end if respond_to? name and not methods.map(&:to_s).include? name.to_s then metaclass.send :define_method, name do |*args, **kwargs| super(*args, **kwargs) end end metaclass.send :alias_method, new_name, name if ENV["MT_KWARGS_HAC\K"] then metaclass.send :define_method, name do |*args, &blk| if val_or_callable.respond_to? :call then val_or_callable.call(*args, &blk) else blk.call(*block_args, **block_kwargs) if blk val_or_callable end end else metaclass.send :define_method, name do |*args, **kwargs, &blk| if val_or_callable.respond_to? :call then if kwargs.empty? then # FIX: drop this after 2.7 dead val_or_callable.call(*args, &blk) else val_or_callable.call(*args, **kwargs, &blk) end else if blk then if block_kwargs.empty? then # FIX: drop this after 2.7 dead blk.call(*block_args) else blk.call(*block_args, **block_kwargs) end end val_or_callable end end end block[self] ensure metaclass.send :undef_method, name metaclass.send :alias_method, name, new_name metaclass.send :undef_method, new_name end