Test Driven Development
To get the most return on your time investment in tests, you should write your tests first and use them to help you as you implement your programs. This idea is known as test driven development. Tests do take some time to write, but if you write them first, you can trade that time to make implementing your program faster and less stressful. There are several reasons for this.
Clarifying Expectations
To write tests, you must know the preconditions and postconditions of the method or unit of code that you’re testing. Preconditions are what you assume is true before the method is run. Postconditions are any return values and the state of the object or other side effects of the method. By writing the tests, you’ll have to ensure that you fully understand the method’s behavior. Coincidentally, in order to correctly implement a method, you have to ensure that you fully understand the method’s behavior!
Furthermore, writing tests will help you determine what kind of invalid input is reasonable to expect and handle.
Test as You Go
Once you have tests written, developing your program becomes much easier. After you implement each method, you can simply run your tests to verify it is correct and verify that you didn’t accidentally break any of your other methods. Running a test suite takes very little time when compared with trying to manually check your method.
Test if You Modify
Code is very rarely written and never touched again. Programs are frequently updated with new features or modifications of old features. Similar to when you first implement a program, updating the tests first lets you flesh out exactly what will need to change and how. Then you already have tests to ensure that your new methods and modified methods work correctly and nothing else broke in the process of updating!
A program development methodology in which the tests are written before the implementation of the program.
A condition that must be true at some point in the execution of a program, in order for the program to proceed correctly from that point. A precondition of a subroutine is something that must be true when the subroutine is called, in order for the subroutine to function properly. Subroutine preconditions are often restrictions on the values of the actual parameters that can be passed into the subroutine.
A condition that is known to be true at some point in the execution of a program, as a result of the computation that has come before that point. A postcondition of a subroutine is something that must be true after the subroutine finishes its execution. A postcondition of a function often describe the return value of the function.