Site icon Dhanendran's Blog

TDD; The Right Way

Many people and many online blogs, books will argue Test Driven Development (TDD) is a process of writing software that proves and satisfies the requirements. But I would say it’s a practice and a mindset which is more than a process.

It’s a mindset to follow a certain process to achieve the greatest thing, quality software. It involves a lot of commitments and focus.

It’s always easy to write the functionality and make the software work. Obviously that’s what every developer wants to do. But TDD works in a different way to get the quality software.

The TDD process goes like this;

  1. Start with a requirement statements
  2. Write tests for the requirements to prove it
  3. Run and watch the test fails
  4. Write the implementation code
  5. Run and watch the test passes
  6. Improvise the code if necessary and confirm the tests passes

This approach is widely known as Red, Green and Refactor.

Red Green Refactor

Frameworks!!!???

Okay, I’m kind of ready to try this practice of Test Driven Development, but which framework should I choose?

Good question. The answer is “it doesn’t matter”. Yes, you heard it right.

There are plenty of frameworks available for testing. You can choose anything which is easy for you and meet the expectation of testing. Because at the end you are the one who gonna implement this approach, not the framework.

Let’s take an example; the requirement is to have a function which should add two numbers and return the value (very complex requirement 😉 ).

$this->assertEquals( 5, addMe( 2, 3 ) );

This will throw an error that addMe() function doesn’t exist. So first create an empty function.

function addMe( x, y ) {
    // logics goes here.
}

Now run your test and watch that fails. Then we should write our logic to meet the requirements.

function addMe( x, y ) {
    return x + y;
}

Now again run the test to see them pass :). Then try to refactor the code for better performance and security.

function addMe( int x, int y ): int {
    return x + y;
}

The test shouldn’t fail even after multiple refactors. That’s it you got it.

It will be a bit tricky and hard in the initial phase, but once you get used to it then nothing will stop you following this approach.

tada; thanks for reading and happy TDD mindset.

Exit mobile version