Minitest是否类似于RSpec中的allow_any_instance_of?

问题描述 投票:0回答:1

来自Docs

rspec-mocks提供了两种方法,allow_any_instance_ofexpect_any_instance_of,可以让您存根或模拟任何内容 类的实例。它们用于代替允许或期望:

allow_any_instance_of(Widget).to receive(:name).and_return("Wibble")

是否有与此功能相似的地方,可以为带有Minitest的类的所有实例模拟方法?

ruby rspec minitest
1个回答
0
投票

根据Minitest文档,您只能模拟单个实例。

https://github.com/seattlerb/minitest#mocks-

没有看到完整的代码,很难判断,但是可能会改进您的体系结构。例如,您可以使用依赖注入来避免使用allow_any_instance_of并使类更具扩展性。

代替做

class Foo
  def initialize
    @widget = Widget.new
  end

  def name
    widget.name
  end
end

并在测试中做

it "does expect name" do
  allow_any_instance_of(Widget).to receive(:name).and_return("Wibble")

  Foo.new.name
end

您可以像这样注入小部件类

class Foo
  def initialize(widget_class = Widget)
    @widget = widget_class.new
  end

  def name
    widget.name
  end
end

以及您的规格

it "does expect name" do
  widget = double()
  widget.stub(:name) { 'a name' }

  foo = Foo.new(widget)

  expect(foo.name).to eq('a name')
end

代码现在遵循开闭原则,并且更具扩展性。但是很难判断这是否对您来说是可行的解决方案。

在[https://sourcediving.com/testing-external-dependencies-using-dependency-injection-ad06496d8cb6的博客文章中对此进行了总结

© www.soinside.com 2019 - 2024. All rights reserved.