65

在我的测试中,我想为类的任何实例存根固定响应。

它可能看起来像:

Book.stubs(:title).any_instance().returns("War and Peace")

然后,每当我调用@book.title它时,它就会返回“战争与和平”。

有没有办法在 MiniTest 中做到这一点?如果是的话,你能给我一个示例代码片段吗?

还是我需要摩卡之类的东西?

MiniTest 确实支持 Mocks,但 Mocks 对于我需要的东西来说太过分了。

4

8 回答 8

43
  # Create a mock object
  book = MiniTest::Mock.new
  # Set the mock to expect :title, return "War and Piece"
  # (note that unless we call book.verify, minitest will
  # not check that :title was called)
  book.expect :title, "War and Piece"

  # Stub Book.new to return the mock object
  # (only within the scope of the block)
  Book.stub :new, book do
    wp = Book.new # returns the mock object
    wp.title      # => "War and Piece"
  end
于 2013-01-07T21:46:56.653 回答
28

我使用 minitest 进行所有 Gems 测试,但使用 mocha 进行所有存根测试,可能可以使用 Mocks 在 minitest 中完成所有操作(没有存根或其他任何东西,但 mock 非常强大),但我发现 mocha 可以干得好,如果它有帮助:

require 'mocha'    
Books.any_instance.stubs(:title).returns("War and Peace")
于 2011-08-28T07:18:09.537 回答
26

如果您对没有模拟库的简单存根感兴趣,那么在 Ruby 中很容易做到这一点:

class Book
  def avg_word_count_per_page
    arr = word_counts_per_page
    sum = arr.inject(0) { |s,n| s += n }
    len = arr.size
    sum.to_f / len
  end

  def word_counts_per_page
    # ... perhaps this is super time-consuming ...
  end
end

describe Book do
  describe '#avg_word_count_per_page' do
    it "returns the right thing" do
      book = Book.new
      # a stub is just a redefinition of the method, nothing more
      def book.word_counts_per_page; [1, 3, 5, 4, 8]; end
      book.avg_word_count_per_page.must_equal 4.2
    end
  end
end

如果你想要一些更复杂的事情,比如对一个类的所有实例进行存根,那么它也很容易做到,你只需要有点创意:

class Book
  def self.find_all_short_and_unread
    repo = BookRepository.new
    repo.find_all_short_and_unread
  end
end

describe Book do
  describe '.find_all_short_unread' do
    before do
      # exploit Ruby's constant lookup mechanism
      # when BookRepository is referenced in Book.find_all_short_and_unread
      # then this class will be used instead of the real BookRepository
      Book.send(:const_set, BookRepository, fake_book_repository_class)
    end

    after do
      # clean up after ourselves so future tests will not be affected
      Book.send(:remove_const, :BookRepository)
    end

    let(:fake_book_repository_class) do
      Class.new(BookRepository)
    end

    it "returns the right thing" do 
      # Stub #initialize instead of .new so we have access to the
      # BookRepository instance
      fake_book_repository_class.send(:define_method, :initialize) do
        super
        def self.find_all_short_and_unread; [:book1, :book2]; end
      end
      Book.find_all_short_and_unread.must_equal [:book1, :book2]
    end
  end
end
于 2012-04-26T07:37:41.157 回答
24

您可以轻松MiniTest. 信息可在github 上找到。

因此,按照您的示例并使用Minitest::Spec样式,这就是您应该如何存根方法:

# - RSpec -
Book.stubs(:title).any_instance.returns("War and Peace")

# - MiniTest - #
Book.stub :title, "War and Peace" do
  book = Book.new
  book.title.must_equal "War and Peace"
end

这是一个非常愚蠢的例子,但至少给了你一个关于如何做你想做的事情的线索。我使用MiniTest v2.5.1进行了尝试,这是Ruby 1.9附带的捆绑版本,似乎在此版本中尚不支持 #stub 方法,但后来我尝试使用MiniTest v3.0,它就像一个魅力。

祝您好运并祝贺您使用MiniTest

编辑:还有另一种方法,即使它看起来有点hackish,它仍然是您问题的解决方案:

klass = Class.new Book do
  define_method(:title) { "War and Peace" }
end

klass.new.title.must_equal "War and Peace"
于 2012-05-24T16:05:41.087 回答
19

只是为了进一步解释@panic 的答案,让我们假设您有一个 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

因此,对于任何特定实例,调用存根方法的次数超过指定的 raises 次数MockExpectationError: No more expects available

此外,对于任何特定实例,调用存根方法的次数少于指定的 raises 次数MockExpectationError: expected title(),但前提是您#verify此时在该实例上调用。

于 2016-06-23T12:04:07.707 回答
17

您不能存根一个类的所有实例,但您可以存根给定对象的任何实例方法,如下所示:

require "minitest/mock"

book = Book.new
book.stub(:title, 'War and Peace') do
  assert_equal 'War and Peace', book.title
end
于 2015-03-13T22:12:03.487 回答
5

你总是可以在你的测试代码中创建一个模块,并使用包含或扩展到猴子补丁类或对象。例如(在 book_test.rb 中)

module BookStub
  def title
     "War and Peace"
  end
end

现在您可以在测试中使用它

describe 'Book' do
  #change title for all books
  before do
    Book.include BookStub
  end
end

 #or use it in an individual instance
 it 'must be War and Peace' do
   b=Book.new
   b.extend BookStub
   b.title.must_equal 'War and Peace'
 end

这允许您将比简单存根可能允许的更复杂的行为组合在一起

于 2015-07-28T09:39:42.290 回答
1

我想我会分享一个基于此处答案的示例。

我需要在一长串方法的末尾存根一个方法。这一切都始于一个 PayPal API 包装器的新实例。我需要存根的调用本质上是:

paypal_api = PayPal::API.new
response = paypal_api.make_payment
response.entries[0].details.payment.amount

我创建了一个返回自身的类,除非方法是amount

paypal_api = Class.new.tap do |c|
  def c.method_missing(method, *_)
    method == :amount ? 1.25 : self
  end
end

然后我把它存入PayPal::API

PayPal::API.stub :new, paypal_api do
  get '/paypal_payment', amount: 1.25
  assert_equal 1.25, payments.last.amount
end

您可以通过创建哈希并返回来使这项工作不仅仅用于一种方法hash.key?(method) ? hash[method] : self

于 2016-03-11T21:40:58.653 回答