Mocking in a mock-shell (oops... nut-shell)

Mocking is a term used to describe a wide array of types, which is inaccurate.

Well, now that everyone uses it as a general term, I assume it is ok to have one word to rule them all, but still, just for the sake of accuracy I will post here a short explanation.

When doing mocking today, we usually use a mocking framework eg: Mockito etc...

This framework allows the developer to mock an object for testing (or any other) purposes.


Why mock ?

Why will we want to mock an object instead of using the original one ?
Maybe the original one is very complex
Maybe the original one demands resources we don't want to mess with
Maybe using the original one can have a restriction on our code
Other things...


So we want to use mocks.

What can we do with them ?

Sometimes we want to construct an object which needs an other object in it's constructor's argument list, we will just mock that argument and send it to the constructor - quick and easy.

Sometimes we want to mock an object and make sure that everytime someone calls a certain method in this object a specific resposnse will be returned (stub)

And for testing purposes we might want to spy on an object in order to see which of it's methods was called (and how many times) (spy)

After the above introduction, I will just say that mocks are generally described as test doubles.


And just to make things a little more accurate I will define the following subsets of mock:

Definitions

Dummy (mock): A test double with no use at all except being of a specific type - usually used to send as an argument.

Stub (mock): A test double which returns a specific response when someone will call a specific method of it.

Spy (mock): A test double with a counter mechanism which can be verified to tell the user how many time a specific method was called.




Just to clarify: 

Today when using a Mocking framework, we will create a mock for any of the above three types of a mock, so sometimes we will mock an object for it to be a dummy, sometimes we will mock an object in order to stub it, and sometimes we will mock an object in order to verify how many times a specific method was called (and sometimes for all three targets) - in any one of those cases the creation of the mock object will be the same, and although the object will be called a "mock" it will might have a different purpose each time.



P.S.
I am adding here a link to the best article about mocking I could find - "The little mocker" by Uncle-bob

Comments

Popular posts from this blog

Start Working with AutoIT

How to read Android apk contents

SCummVM for Android