简体   繁体   中英

Verify method never called or only once called using Minitest::Mock

Is there any way to verify a method never called or only a number of times called using Minitest::Mock

Thanks in advance

Specific number of times: Minitest::Mock forces the developer to be explicit about message expectations, so if you expect a given method to be called x times, you'll need to be very literal about it.

my_mock = Minitest::Mock.new
x.times { my_mock.expect :some_method, :return_val }

Never called: Philosophically, Minitest shies away from testing that something doesn't happen. While it's not completely analogous, have a look at this post or google "minitest assert nothing raised".

Minitest::Mock will raise a NoMethodError whenever an unexpected method is called on it. That's not exactly an assertion, but probably has the desired effect. Still, you don't particularly need a mock to do what you're asking. You can do the same by patching your real object instance.

def test_string_size_never_called
  str = "foo"
  def str.size
    raise NoMethodError, "unexpected call"
  end

  # test logic continues...
end

Was looking for a "proper" way to test that something isn't called in minitest (I hate minitest) and stumbled upon this question.

I ended up doing it like this:

def test_foo_isnt_called
  Foo.stub(:call, proc { raise "shouldn't happen" }) do
    subject(x, y)
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM