This article is a simple explanation of mock and stub used in unit testing.
๐ What is stub?
- A stub is a small program routine that substitutes for a longer program.
- You should use a stub in order to pass to the code under test.
๐ What is mock?
- Mock is a method/object that simulates the behavior of a real method/object.
- A mock is an object that we can set expectations on, and which will verify that the expected actions have indeed occurred.
๐ฐ Why do need mock/stub?
As for why it is necessary to reproduce method / object:
- If you try to test everything with โreal method/dataโ, you have to prepare all processing and data.
- To make it easier to test objects like time.
๐ Example of stub
If you want to return a specific value when a method of an object is called, prepare a stub like the following:
# When Foo#method is invoked, :return_value will be returned |
For example, if you write like this, โcount method of Array class will always return 20โ.
test_array = [] |
๐ฏ Example of mock
If you want to expect that a method is called with :argument, and want to return โ:return_valueโ when called, you should prepare the following mock:
allow(Foo).to receive(:method).with(:argument).and_return(:return_value) |
Mock of instance method is as follow:
allow_any_instance_of(Foo).to receive(:method).and_return(:return_value) |
The mock that generates the error like this:
allow(Foo).to receive(:method).and_raise("boom") |
๐ Special Thanks
- Raising an error - Configuring responses - RSpec Mocks - RSpec - Relish
- ruby on rails - RSpec: Stub private method - Stack Overflow
๐ฅ Recommended VPS Service
VULTR provides high performance cloud compute environment for you.
Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour).
In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!