Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Tomek Kaczanowski - Practical Unit Testing with JUnit and Mockito - 2013.pdf
Скачиваний:
224
Добавлен:
07.03.2016
Размер:
6.59 Mб
Скачать

Chapter 4. Test Driven Development

first it should fail, thus repeating the observed buggy behaviour. Later on, you should fix the code so the test passes.

If you think about it, you will realize that writing a test after a bug has been found really amounts to a test-first approach. You write a test which fails (because you want to mimic the bug), and then you implement the code.

The big issue here is to pinpoint the bug precisely, so that you are able to write a unit test which exposes it. This might be really tricky. It may be that multiple bugs are turning up in your business logic in the course of your clicking the UI of your application. It is not so easy to tell exactly which class is responsible for some particular bit of erroneous behaviour. This is usually solved by first writing a higher-level test (i.e. an end-to-end test), and then gradually gathering information on the cause, narrowing the search field by writing more focused tests: first integration, and then eventually unit, tests.

4.2. TDD Rhythm

The nice thing about test-first coding is that it consists of a few very simple steps repeated over and over again. And – which comes as quite a surprise the first time one encounters it – these simple steps lead to a great coding experience and great results. Pure magic, isn’t it?

Now, I would like you to take a look at Figure 4.1. This picture is simplified. It does not tell the whole truth. We will enhance it further to include some more details. Yet, this is THE picture that should hang over your desk2. It gives you the rhythm of your work:

1.Write a test that fails (RED).

2.Make the code work (GREEN).

3.Eliminate redundancy (REFACTOR).

It also gives you a simple rule to follow: never write code without a failing test!

Figure 4.1. The most important picture

The next picture - Figure 4.2 - gives some more insight into the TDD rhythm. It shows how you start with a list of tests, choose one of them, and then follow the red-green-refactor cycle, making sure you end up with green.

2If I had to choose one thing that I would like you to remember from this book, it would be this picture!

41

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]