Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing: Explain the usefulness of Mock Objects [duplicate]

Possible Duplicate:
What is Object Mocking and when do I need it?

like image 218
Stephen Avatar asked Nov 26 '10 22:11

Stephen


2 Answers

You might indeed start writing tests for B and implementing B as soon as you know you need it and then come back to A. But when you come back to A you might want to use a mock for B so that your test for A is really testing A and its interactions with B.

Part of the reason for this is there might be another class C that B uses to do some of its work. If you want to test A using a real B, you'll also need C, and of course the difficulty can extend further.

Using mocks you can make your test check only that A calls B methods when it should and deals properly with the responses that you tell your mock to give, rather than depending on a real implementation of B.

like image 64
Don Roby Avatar answered Sep 21 '22 13:09

Don Roby


To learn better how to use Mocks and in general TDD I recommend you nat pryce blog and his book http://www.natpryce.com/

Generally speaking it's not a good idea to use too much mocks. Use them when you have to isolate layers of your applications (db and view i.e.) or external (slow) system.

Writing mocks could make your tests hard to read, so it's better not abuse them.

like image 22
Uberto Avatar answered Sep 20 '22 13:09

Uberto