In the part 1, I talked a little bit about the concept of tests… Now we’re going to see in practice.
FYI: For this example, I used JUnit 4 and Eclipse.
We learned that the TDD flow is Red, Green and Refactor, but today I will add a new concept called Baby Steps.
They are the smallest steps to solve a problem. In our case, the smallest possible piece of code to solve the problem. We’re going to break the paradigm of Red, Green and Refactor, just a bit, to demonstrate in practice these small steps. And before going into practice, there’s one last concept that I learned from my boss and is very helpful.
- Briefly: Make it work for 1 case. Then, make it work for 2 cases. Then, for N cases.
- Let’s create a test for a method add (sum) of a calculator.
With JUnit4 already configured, when we create a test class by Eclipse (JUnit Test Case), the created class looks kinda like this:
Running the test (Alt + Shift + X, T), we see that the test fails as configured.
Actually, this is only the introduction to test classes. Let us set up our real test now. When we add 1 to 1, we hope that the result is 2. Let’s do it in our test class. For this, we also create the Calculator class that will NOT have implementation yet.
The test fails. In the error message you can see that the expected value was 2 but the method returned 0. The smallest step possible to solve the problem is to solve that specific test. Baby steps. So let’s just return 2 and rerun the tests.
We see that the test worked. But the code is still bad. We could refactor now, as the paradigm of TDD says, but to teach better Baby Steps and 1-2-N, let’s leave it for now, because the code still works only for one case. Following the concept 1-2-N, the next step is to work for 2 cases.
When we add another test and we ran, there’s just one test working because we expect a different value returned. Following Baby Steps, we could solve the problem as follows:
The tests ran with success. Again, we could refactor the code, but we will continue just a little longer. According to the concept 1-2-N, let’s make it work with over 2 cases. Let’s add a last test:
The tests fail, since it only works for the 2 cases. Following again the Baby Steps, a possible solution to the problem could be that:
The tests work. However, the code is ugly. But we know that the test works. And for 1, 2 or N cases. We’ll finally refactor the code.
The tests ensure that the method works as expected, then again we run the tests all the tests work.
Appendix: Code Coverage
You can also use code coverage tools, showing which parts of the classes have been tested and which were not, what piece of code is not being tested or used for the tests, also show the percentage of tested code. In my opinion, as well as the tests, are indispensable.