Wednesday 23 May 2012

Test Driven Development: You are going to shoot me now but be PRAGMATIC


Test driven development (TDD) is more than just writing unit test cases to make to us happy when the progress bar goes red to green. It promotes writing clean code and demotes unnecessary documentation. Code refactoring enables clean code - helps to find the simplest design of your class. Test cases written against your class in itself describe intention. Why do you need to document class description unnecessarily. 

No need to write test cases for all the classes:
Having said that we need to be pragmatic. I know not all of you agree with me - there is no need to write test cases for all the classes  you will be implementing! You are not going to shoot be now yet :) I think the better approach would be to identify classes that are responsible for implementing business rules. Business rules often change thus requires changes in classes. The beauty of TDD comes into play now. Your hard work starts to pay you off. You can run test cases you have written which automatically there and then warns you if new changes has broken other part of system or not. Bingo - regression testing is so sweet now.

Mock or not to Mock:
Mocking framework assists in situation when your class depends on external services - database calls, file system manipulation, invoking web services etc. Fundamental idea is that your code is working fine as long as the value you are expecting from dependent system is correct! It helps to satisfy TDD principle - unit test case shouldn't take more than 10 millisecond to execute. More over continuous build shouldn't take more than 10 minutes to generate a new build. All sounds good. My worry is that we are given a false security. I have to be bold. Therefore if possible avoid mocking. Don't shoot me please. I am trying to be practical and just want to make sure my system is working as it should. As an example, imagine you have written data access repository classes. How do you say that it's meeting business requirements unless you have written test cases against those classes allowing to hit the database? Am I not asking a valid question? If you are on the same boat as I am then I follow simple rule - reset database to known state, run your test cases and wait for the bar to go green!

[TestFixture]
public class DbTest
{
      [SetUp]
public void ResetDatabaseToKnownState()
{....}

      [TearDown]
public void CleanUpYourDirt()
{...}

[Test]
        public void DoTestHittingDb()
{..}
}

Thanks,
Milan Gurung

2 comments:

  1. I agree taht code refactoring enables clean code - helps to find the simplest design of your class. But I did not work with refactoring enables clean code, I read information about this, also about mobile application development - read more

    ReplyDelete