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:

# 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”.

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:

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

🖥 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!!