After understanding what is Unit Testing
, its time to answer some of the "Whys"
“Understanding what your Unit is is supposed to do”! Yes, that’s one of the primary reasons why we need to write unit tests before writing the methods themselves. When you sit down to write a piece of code, you have a mental image of what functionalities that piece of code should accomplish, but not all the exceptional conditions your code should handle. Once you write your code you have to make sure, that the code is fulfilling your intent. The reason for writing unit testing first will make sure that you are clear about your intent
. Most of the time as developers we start coding as soon as we have a partial idea of what the unit is suppose to do (without having a clear intent).
For example, say you want to write a substring function, we will immediately sit down to code the best case scenario, the happy path. What about other cases, if the String is null, if the indexes are negative values, if the To index is less than the from index, if the index specified is outside the boundary of String object, if the From index is equal To index. Including the happy path now we have 6 different cases our code should handle. It should handle all these cases all the times. Through writing Unit Test cases first we are making sure, that we understand what our method is suppose to do. That’s why unit testing is considered a programming technique, rather than testing technique. Not only unit testing helps you to understand what the method suppose to, it also ensures that you code what you intended, since every time you modify the code you will be running the unit test cases against it to make sure that your code does not break any of them and thus making sure your code performs up to your intent.
Unit tests are performed to prove that a piece of code does what the developer thinks it should do.
posted by 88Pro / Monday, May 24, 2004