Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocks and Stubs

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.

like image 905
Anand Avatar asked Mar 02 '11 06:03

Anand


People also ask

Are stubs same as mocks?

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.

What is a stub example?

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 are mocks in testing?

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.

What is the difference between stubs and mocks in Ruby testing?

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.


1 Answers

My very simplified answer is:

  • mocks are objects that have a similar interface as something else
  • stubs are fake methods and return a specific answer

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.

like image 139
nathanvda Avatar answered Sep 22 '22 10:09

nathanvda