The second test and first refactoring.
Having completed the first test, it is time to start the second test.
The Second Test
The add function takes a single number and returns that number.
This test can be written completely as at no point does the code fail to compile
This gives us our next failing test. All tests must fail before they pass, this is to ensure that the test actually does something, and is able to fail. Again to make this pass is trivial, first we need to check that the incoming string is not empty, if it is then return zero, this will continue to make the first test pass, then we simply need to return 1, to make the second test pass, the resulting production code looks like this.
All the tests now pass, and we can start to refractor both the test and production code, looking first at the test code we can see some duplication and the call to the add method could be moved to inside the assert call, also the first test assert parameters are the wrong way around!
To remove the duplicated code we use the promote to field refactoring with the field instantiation carried out in a new test setup method which has the test initialize attribute so that it runs before each test.
We can also use the inline variable refactoring to remove the result attribute and call the add method within the assert method call, refactoring unit tests must be carried out carefully as we want to promote readability, so following this we end up with test code that looks like this
All tests still pass, so nothing is broken.
Looking at the production code it can be seen that the add method is now doing at least two things.
the check to see if the input is empty is refactored out into its own method “IsInputEmpty”, and the return zero is refactored into its own method “HandleEmptyInput”
Why am I doing this? Don’t I end up with lots of small methods?
Solid programming principles state that a method should do one thing, and have one reason to change, we can now change the definition of empty input or how empty input is handled, both in totally different methods, so I am satisfying that rule, also by having well named methods the add function is starting to be easy to read, and contains nothing that we would not expect.
This example is again simple, but even so the rules of TDD and Solid can be applied, by practicing these principles in the kata, makes it easier to apply them in real production and test code.