Test Doubles — Fakes, Mocks and Stubs.

Capture1We are looking at testing with Fakes, Mocks and Stubs. A Test Double is automated testing it is common to use objects that look and behave like their production equivalents but are simplified. This reduces complexity, allows to verify code independently from the rest of the system and sometimes it is even necessary to execute self-validating tests at all. The three implementation variations of testing doubles:

Fakes are objects that have working implementations, but not same as production one. Usually they take some shortcut and have simplified version of production code. Fake implementation can come handy for prototyping and spikes. We can quickly implement and run our system with in-memory store, deferring decisions about database design. Another example can be also a fake payment system, that will always return successful payments.

Command Query Separation- Methods that return some result and do not change the state of the system, are called Query. It returns a value and is free of side effects. There is also another category of methods called Command. This is when a method performs some actions, that changes the system state, but we don’t expect any return value from it. For testing Query type methods we should prefer use of Stubs as we can verify method’s return value.

Stub is an object that holds predefined data and uses it to answer calls during tests. It is used when we cannot or don’t want to involve objects that would answer with real data or have undesirable side effects. An object that needs to grab some data from the database to respond to a method call. Instead of the real object, we introduced a stub and defined what data should be returned.

Mocks are objects that register calls they receive. In test assertion we can verify on Mocks that all expected actions were performed. We use mocks when we don’t want to invoke production code or when there is no easy way to verify, that intended code was executed. There is no return value and no easy way to check system state change.

There are more test doubles such as dummy object, test spy. I thought this blog show clear each test and simple example.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s