Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
roth_stephan_clean_c20_sustainable_software_development_patt.pdf
Скачиваний:
29
Добавлен:
27.03.2023
Размер:
7.26 Mб
Скачать

Chapter 8 Test-Driven Development

•\ RED: We write one failing unit test.

•\ GREEN: We write just enough production code—and not one line more!—so that the new test and all previously written tests will pass.

•\ REFACTOR: Code duplication and other code smells are eliminated, both from the production code as well as from the unit tests.

The terms RED and GREEN refer to typical unit test framework integrations that are available for a variety of IDEs (Integrated Development Environments), where tests that passed are displayed in green and tests that failed are shown in red.

Enough of theory, I will now explain the complete development of a piece of software using TDD and a small example.

TDD by Example: The Roman Numerals Code Kata

The basic idea for what is nowadays called a code kata was first described by Dave Thomas, one of the two authors of the remarkable book, The Pragmatic Programmer [Hunt99]. Dave was of the opinion that developers should practice on small, not job-­ related, code bases repeatedly so that they can master their profession like a musician. He said that developers should constantly learn and improve themselves, and for that purpose, they need practice sessions to apply the theory over and over again, using feedback to get better every time.

A code kata is a small exercise in programming, which serves exactly this purpose. The term kata is inherited from the martial arts. In far-eastern combatant sports, they use katas to practice their basic moves over and over again. The goal is to bring the course of motion to perfection.

This kind of practice was devolved to software development. To improve their programming skills, developers should practice their craft with the help of small exercises. Katas became an important facet of the Software Craftsmanship movement. They can address different abilities a developer should have, for example, knowing the keyboard shortcuts of the IDE, learning a new programming language, focusing on certain design principles, or practicing TDD. On the Internet, several catalogues with suitable katas for different purposes exist, for example, the collection by Dave Thomas on http://codekata.com.

For our first steps with TDD, we use a code kata with an algorithmic emphasis: the well-known Roman numerals code kata.

342

Chapter 8 Test-Driven Development

TDD KATA: CONVERT ARABIC NUMBERS TO ROMAN NUMERALS

The Romans wrote numbers using letters. For instance, they wrote “V” for the Arabic number 5.

Your task is to develop a piece of code using the test-driven development (TDD) approach that translates the Arabic numbers between 1 and 3,999 into their respective Roman representations.

Numbers in the Roman system are represented by combinations of letters from the Latin alphabet. Roman numerals, as used today, are based on seven characters:

1 I

5 V

10 X

50 L

100 C

500 D

1,000 M

Numbers are formed by combining characters together and adding the values. For instance, the Arabic number 12 is represented by “XII” (10 + 1 + 1). And the number 2017 is “MMXVII” in its Roman equivalent.

Exceptions are 4, 9, 40, 90, 400, and 900. To avoid that four equal characters must be repeated in succession, the number 4, for instance, is not represented by “IIII”, but “IV”. This is known as subtractive notation, that is, the number that is represented by the preceding character I is subtracted from V (5 - 1 = 4). Another example is “CM,” which is 900 (1,000 - 100).

By the way, the Romans had no equivalent for 0 (zero); furthermore, they didn’t know negative numbers.

Preparations

Before we can write our first test, we need to make some preparations and set up the test environment.

343

Chapter 8 Test-Driven Development

As the unit test framework for this kata, I use Google Test (https://github.com/ google/googletest), a platform-independent C++ unit test framework released under the New BSD License. Of course, any other C++ unit testing framework can be used for this kata as well.

It is also strongly recommended to use a version control system. Apart from a few exceptions, we will perform a commit to the version control system after each pass-­ through of the TDD cycle. This has the great advantage that we can walk back and regress possibly wrong decisions.

Furthermore, we have to think about how the source code files will be organized. My suggestion for this kata is initially to start with just one file, the file that will take up all future unit tests: ArabicToRomanNumeralsConverterTestCase.cpp. Since TDD guides us incrementally through the formation process of a software unit, it is possible to decide later if additional files are required.

For a fundamental function check, we write a main function that initializes Google Test and runs all tests, and we write one simple unit test (named

PreparationsCompleted) that always fails intentionally, as shown in the code example in Listing 8-1.

Listing 8-1.  The Initial Content of ArabicToRomanNumeralsConverterTestCase.cpp

#include <gtest/gtest.h>

int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS();

}

TEST(ArabicToRomanNumeralsConverterTestCase, PreparationsCompleted) { GTEST_FAIL();

}

After compiling and linking, we execute the resulting binary file to run the test. The output of our small program on standard output (stdout) should be as shown in Listing 8-2.

344

Chapter 8 Test-Driven Development

Listing 8-2.  The Output of the Test Run

[==========]

Running 1 test from 1 test case.

[----------]

Global test environment set-up.

[----------]

1

test from ArabicToRomanNumeralsConverterTestCase

[ RUN

]

ArabicToRomanNumeralsConverterTestCase.PreparationsCompleted

../ ArabicToRomanNumeralsConverterTestCase.cpp:9: Failure

Failed

 

 

 

[

FAILED

]

ArabicToRomanNumeralsConverterTestCase.PreparationsCompleted

(0

ms)

 

 

 

[----------]

1

test from ArabicToRomanNumeralsConverterTestCase (2 ms total)

[----------]

Global test environment tear-down

[==========]

1

test from 1 test case ran. (16 ms total)

[

PASSED

]

0

tests.

[

FAILED

]

1

test, listed below:

[

FAILED

]

ArabicToRomanNumeralsConverterTestCase.PreparationsCompleted

1

FAILED TEST

 

Note  Depending on the unit test framework and its version used, the output may be different than what is presented in this example.

As expected, the test fails. The output on stdout is pretty helpful to imagine what went wrong. It specifies the name of the failed tests, the filename, the line number, and the reason that the test failed. In this case, it is a failure that was enforced by a special Google Test macro.

If we now exchange the GTEST_FAIL() macro with the GTEST_SUCCEED() macro inside the test, after a recompilation the test should pass, as shown in Listing 8-3.

Listing 8-3.  The Output of the Successful Test Run

[==========]

Running 1 test from 1 test case.

[----------

]

Global

test

environment set-up.

[----------

]

1 test

from

ArabicToRomanNumeralsConverterTestCase

[ RUN

]

ArabicToRomanNumeralsConverterTestCase.PreparationsCompleted

[

OK ]

ArabicToRomanNumeralsConverterTestCase.PreparationsCompleted (0 ms)

345