Test driven development means, that you first write your tests, and then your program. So you have to think the other way around: ๐ which result do you expect from your functions?
You write the test to check the result of the (not yet existing) function. Then you write your function and run the test. You repeat this in tiny baby steps and switch back and forth between the test and the function or part of code which belongs to the test.
This method has several advantages:
๐นyou only write the code you actually need (no overhead)
๐นyou can find bugs a lot easier when you write good tests, because the failure of the test shows you where you are probably wrong
๐นyour code is more maintainable
In Java you have the framework Junit for example, which makes writing tests easy.
At the top we have the class Calculator, which is in a separate file from the test. We now want to check if the sum function works properly.
So we create a test file, as seen in the code starting with โimport..โ We make an instance of a calculator and call the sum method. It should return 6, so we use the assertEquals method, which checks if โ6โ and โresultโ are equal.
Do you develop test driven? Have a nice day! ๐
Top comments (0)