I really don't understand what Mocks and Stubs are. I want to know when, why and how we use Mocks in our test cases. I know that there are good frameworks out there for Mocks and Stubs in Ruby on Rails, but without knowing the purpose, I'm reluctant to use them in my app.
Can you please clarify about Mocks and Stubs? Please help.
Mocks verify the behavior of the code you're testing, also known as the system under test. Mocks should be used when you want to test the order in which functions are called. Stubs verify the state of the system under test.
A stub is an object that holds predefined data and uses it to answer calls during tests. It is used when you can't or don't want to involve objects that would answer with real data or have undesirable side effects. An example can be an object that needs to grab some data from the database to respond to a method call.
What is mocking? Mocking is a process used in unit testing when the unit being tested has external dependencies. The purpose of mocking is to isolate and focus on the code being tested and not on the behavior or state of external dependencies.
A Test Stub is a fake thing you stick in there to trick your program into working properly under test. A Mock Object is a fake thing you stick in there to spy on your program in the cases where you're not able to test something directly.
My very simplified answer is:
With both we are trying to achieve the same thing: we want to test a specific unit (model/view/controller/module) in isolation. E.g. when we are testing the controller, we do not want to test our model, so we use a mock. We want to make sure the correct methods are called, e.g. find
. So on our mock, we have a stub that will return something predefined, without actually going to the database.
So we test for expectations: the methods that we expect to be called (on other units), without actually calling them. The test of that specific method, should have been covered in its own test.
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