为了进一步解释 @panic's answer,假设您有一个 Book 类:
require 'minitest/mock'
class Book; end
首先,创建一个 Book 实例存根,并使其返回您想要的标题(任意次数):
book_instance_stub = Minitest::Mock.new
def book_instance_stub.title
desired_title = 'War and Peace'
return_value = desired_title
return_value
end
然后,让 Book 类实例化您的 Book 实例存根(仅且始终在以下代码块中):
method_to_redefine = :new
return_value = book_instance_stub
Book.stub method_to_redefine, return_value do
...
在此代码块中(仅),Book::new 方法被存根。让我们试试吧:
...
some_book = Book.new
another_book = Book.new
puts some_book.title #=> "War and Peace"
end
或者,最简洁的:
require 'minitest/mock'
class Book; end
instance = Minitest::Mock.new
def instance.title() 'War and Peace' end
Book.stub :new, instance do
book = Book.new
another_book = Book.new
puts book.title #=> "War and Peace"
end
或者,您可以安装 Minitest 扩展 gem minitest-stub_any_instance。 (注意:使用这种方法时,Book#title 方法必须在你存根之前存在。)现在,你可以更简单地说:
require 'minitest/stub_any_instance'
class Book; def title() end end
desired_title = 'War and Peace'
Book.stub_any_instance :title, desired_title do
book = Book.new
another_book = Book.new
puts book.title #=> "War and Peace"
end
如果您想验证Book#title 是否被调用了一定次数,请执行以下操作:
require 'minitest/mock'
class Book; end
book_instance_stub = Minitest::Mock.new
method = :title
desired_title = 'War and Peace'
return_value = desired_title
number_of_title_invocations = 2
number_of_title_invocations.times do
book_instance_stub.expect method, return_value
end
method_to_redefine = :new
return_value = book_instance_stub
Book.stub method_to_redefine, return_value do
some_book = Book.new
puts some_book.title #=> "War and Peace"
# And again:
puts some_book.title #=> "War and Peace"
end
book_instance_stub.verify
因此,对于任何特定实例,调用存根方法的次数超过指定次数会引发 MockExpectationError: No more expects available。
此外,对于任何特定实例,调用存根方法的次数少于指定次数会引发 MockExpectationError: expected title(),但前提是您当时在该实例上调用 #verify。