Table of Contents
The reference book is Test Driven Development By Example [ Kent Beck ], and the Japanese version is テスト駆動開発入門.
This time, let’s talk about the essence of testing. I wrote down the important points while writing tests, implementing code, and adding functionality. This is a continuation of the procedure for writing tests first in test-driven development.
Write Asserts First
When writing tests, it seems best to start with Asserts. Indeed, starting from the goal is a common practice.
When starting with Assert, the first two things to consider are:
- What is the right answer? (What makes it correct?)
- How am I going to check it? (How do I check it, and what value do I check?)
Looking at the examples in the book, you can see that they start with these two points, write tests using non-existent classes from the Assert part, and finally complete the tests.
Test Data
According to Kent Beck, there are also rules for the data used in tests. It is said that easily understandable data, such as 1 or 2, should be used if possible.
Also, depending on the system, real data may be used in testing. Kent Beck mentions that real data is particularly effective in the following cases:
- When testing real-time systems that use data output from other systems in operation.
- When comparing output between the program before the change and the program after the change.
It’s not a particularly difficult topic, but let’s organize it in our minds for now.
Rules for Implementing Tests
Test code may deviate from general programming rules. For example, magic numbers. This is because the purpose of testing is to complete the implementation code and obtain feedback from the test as needed. As mentioned in the “MONEY EXAMPLE” chapter, they initially completed the test by using magic numbers.
The methods enumerated in the “MONEY EXAMPLE” chapter are explained again. There are “Fake It” and “Triangulation,” but the one you must understand first is “Fake It.”
Fake It (‘Til You Make It)
An example from when a testing framework was created in Python is introduced on page 102 of the English version. The part where the test code gradually changes from being fake is reprinted.
Kent Beck lists the following two merits of “Fake It.” The second one was also mentioned a little earlier.
- First, by making the test green, you can be confident in your code. You don’t have to worry unnecessarily.
- Even if it’s obvious, by writing tests and making them green, you can easily see what functionality is currently lacking.
From there, the discussion continues to “Triangulation.” Since it’s a review of the story that appeared in the “MONEY EXAMPLE” section, I’ll skip it.
Adding Parameters
There is an example of how to write test code when adding functionality after the test is completed, such as changing from sum(int value)
to sum(int[] values)
. Of course, it’s an artificially created method, so there are some unnatural parts, but you should grasp the overall flow.