Hi there, in this post we will talk a little bit about Unit testing and TDD. I just started out using it whenever I can, that is in my own projects because in my daily work we never practice TDD. Sigh!
TDD (Test Driven Development)
TDD is a method of writing software which results to writing source code as bug free as possible and which makes development and delivering finished products way faster due to this fact (overall time becomes less and less using this technique eventually). The benefits of TDD are not limited only to the latter. It forces you to become a better developer because it makes you think well before you implement, better structure your code design and architecture. This is done by pushing you to write functions or other building blocks of your project as small and simple as possible, so they can be easily testable. I will give you an example for you to see what’s going on and talk about the process afterwards.
So, this above is the finished file. We will break it down and talk about what we did and why we did it in the following paragraphs. The process we followed above is called Unit testing and the units in our example are the two functions average() and sum().
Steps of unit testing
The first step when writing tests is to figure out the requirements you need to meet and which are asked by your client or manager or boss. In our example we need to implement two functions: one in order to use it as a tool for summing up an array of elements (we preassume that they are numbers). The second one is a function which gives us the average of the numbers array.
Unit tests seem like pseudocode but they mostly care about inputs and outputs! If you take a certain input you expect to have a certain output. So, the second step is to write our two assertions, one for each function.
The final step of the process is to write the actual functions until all our tests pass!
NOTE: we could write some more tests checking about the inputs we get. If it is an array and if it is an array of numbers etc. to be more sure we write the most adequate sum and average functions we possibly can!
So, this is a simple example of Unit testing!