This article is a simple explanation of mock and stub used in unit testing.
- 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.
- 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.
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.
If you want to return a specific value when a method of an object is called, prepare a stub like the following:
For example, if you write like this, “count method of Array class will always return 20”.
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:
Mock of instance method is as follow:
The mock that generates the error like this:
- Raising an error - Configuring responses - RSpec Mocks - RSpec - Relish
- ruby on rails - RSpec: Stub private method - Stack Overflow