Posted by Anuraj on Wednesday, March 19, 2014 Reading time :3 minutes
Test-driven development (TDD) is a software development process that relies on the repetition of a very short development cycle: first the developer writes an (initially failing) automated test case that defines a desired improvement or new function, then produces the minimum amount of code to pass that test, and finally refactors the new code to acceptable standards. Here is fundamental mantra of TDD:
This technique also referred as “Red-Green-Refactor” because IDEâ€™s and test runners use red color to indicate failed tests and green color to indicate the tests that passed.
First you need to create the Test Runner, it can be an HTML file, which contains links to the QUnit Framework and your test cases. Here is the code for minimal test runner.
This DIV with Id “qunit” will display the results. And the DIV with id “qunit-fixture” will display any test case related information.
Now you need to start writing tests. For the demo purposes I am creating an Age calculator, which will take your Date of Birth as the argument and returns the number of years. Here is my calculator class.
And here is my first unit test, which will verify the GetAge function exists or not.
And open the test runner HTML. As we don’t have a function like that, it will fail.
Now you to write minimal code to pass the test.
Here is the calculate function which doesn’t not do anything, but helps to pass the first test. Now open the test runner again, and refresh the page.
Now you need to write a test which will verify the functionality, like the Calculate function should return a positive integer.
As expected this test will also fail, because we don’t have anything implemented in the Calculate function. Now let’s write some code to pass this test as well.
Now the second test will pass.
Now we can do some refactoring the unit tests, if you look into the test code, we are are duplicating the initialization of AgeCalculator. Either you can create a method which will return the instance, and call the function in the initialization or you can create a QUnit module and can use the framework feature for initialization before running every tests.
Here is the implementation.
And here is the screenshot for the same.
Here is links which may help you.
Happy Programming :)