Is there any way to verify a method never called or only a number of times called using Minitest::Mock
Thanks in advance
Verify in Mockito simply means that you want to check if a certain method of a mock object has been called by specific number of times. When doing verification that a method was called exactly once, then we use: verify(mockObject).someMethodOfMockObject(someArgument);
When doing verification that a method was called exactly once, then we use: ? If the method was called multiple times, and you want to verify that it was called for specific times, lets say 3 times, then we use: ? times () means the number of invocations you expect.
If you want to test that a certain method was called (or in some instances NOT called) you will need to use a mocking library. When writing C#, Moq is a great tool. Moq provides a method called Verify () that will allow you to test if a mocked object has been used in an expected way.
We can use Mockito verify methods at the end of the testing method code to make sure that specified methods are called. Mockito verify () method can be used to test number of method invocations too. We can test exact number of times, at least once, at least, at most number of invocation times for a mocked method.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With