What are mock and stub used in unit testing?

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:

1
2
# When Foo#method is invoked, :return_value will be returned
allow(Foo).to receive(:method).and_return(:return_value)

For example, if you write like this, “count method of Array class will always return 20”.

1
2
3
4
test_array = []
test_array.stub(:count).and_return(20)
puts test_array.count #=>20

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:

1
allow(Foo).to receive(:method).with(:argument).and_return(:return_value)

Mock of instance method is as follow:

1
allow_any_instance_of(Foo).to receive(:method).and_return(:return_value)

The mock that generates the error like this:

1
allow(Foo).to receive(:method).and_raise("boom")

Special Thanks