Definition
A test by definition everyone knows what it is. The most important here is "unit", "unit" for an unit, an unit test is a test which will test an unit of independent code of an other. The test must verify the good working of a method for a specific case.
The unit test is not done by the end user of the project but code that will test the code of the software that you are building. At the first look it seems odd but when you do it one time, you will want to do it always.
How to do it
Steps
All steps are a part of the following iteration:
- Decide a method to write
- Create a tests list
- Take a test from the list and implement it
- Check that the test code builds and check that the result of the test is red
- Implement the code (doing refactoring if we are not at the first iteration) which will change the result of the test to green
- Run the test and check that the result of the test is green
Sample
We will decide to write a method to do a division of 2 numbers. In the code we write only the signature of the method and the minimum so the code builds:
public double Divide(int a, int b):
- I create the following tests list ::
- To check that the division of the 2 numbers is correct
- To check that the division by 0 throws the good exception.
- The tests list must cover at least the documentation of the method that we are writing, it is the contract of the method. It is possible that you add documentation to the method when writing the test.
next delete the automatic created class in this project and add a new Unit Test
The next screen lets you choose different classes, choose the method to test
The skeleton of the test is now created
We adapt the code to check that the result of the division of 6 by 2 is well 3 and we run the test to check that it builds and that is red.
Now we adapt the code so the result is green, we write only the code to make the test become green and no more code, it's important so all the code is tested.
Now we take the next test and we do the same steps, write the test, checks that it's red, implements the code and now we can also do refactoring and we finally check that the test is green.
- The tests list must cover at least the documentation of the method that we are writing, it is the contract of the method. It is possible that you add documentation to the method when writing the test.
Post a Comment