Why don’t you use Mocks?

In a developer’s life, he might work on numerous projects. Some are truly greenfield, some are not so much and some are absolutely not. I would bet that most projects we developers end up have already got quite a bit of code base already in place. Doing a proper Test Driven Development (TDD) means writing your tests before your code and then repeat process improving the code base test by test. Well if you see in case of projects that are fairly matured or in their maintenance stage, not all parts of the project can be pure TDD anymore. One would get an opportunity when a new feature is requested or a requirement changes to get his hands on implementing TDD in a restricted kind of way.

With that fact out of the way, the other day one of my colleagues had a hallway talk with me “You know we have been really slacking on our unit tests. For our new feature XYZ, we should follow proper unit testing cycles”. Umm… sure. “Ah and yes, please use Mocks ok”. WTF! There is a general belief among certain set of developers/leads that if they see unit tests with usage of some Mocking Framework, the tests must be well written and are strong. Experienced TDD practitioners must already be spitting bullshits all over this blog post, but really I have heard and seen this a lot. Most of the times, I have seen tests where the intention was to actually have some dummy implementation of some class as a placeholder but still went ahead to use a mocking framework. Now there is nothing wrong here, one can use a mocking framework to create a “Stub” but then that is not the main reason why mocking frameworks exist. The high order bit when it comes to mocks is “Behaviour Testing”. Testing that involves checking the interaction between objects in your component is best done with a mocking framework. If a default implementation is your sole intention, then as long as your code is well written with inversion of control pattern, a dependency injection container can do the job. See this,

public void TestIsThisMockingAtAtll()
{
var mock = new Mock();
var d = new DataAccess(mock.Object);
Assert.AreEqual(5, d.GetDataItems().Count());
}


I would say we have not done any behavioural testing here. All we have done here is create a stub object and used to do some state testing on the DataAccess class. If you have such tests and you claim you are using mocks heavily in your tests, you are creating a mockery of yourself Angry smile.

Happy Mocking!

Abhang Rane


No comments :

Post a Comment

Leave a Comment...