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

Chapter 4. Test Driven Development

Listing 4.5. Refactored FootballTeamTest

public class FootballTeamTest {

private static final int THREE_GAMES_WON = 3;

@Test

public void constructorShouldSetGamesWon() {

FootballTeam team = new FootballTeam(THREE_GAMES_WON);

assertEquals(THREE_GAMES_WON + " games passed to constructor, but " + team.getGamesWon() + " were returned",

THREE_GAMES_WON, team.getGamesWon());

}

}

4.5.5. First Cycle Finished

We have just finished the first TDD cycle. Everything started with that failed test. Then we worked on the error message and fixed the code. After the test passed, we refactored the code (and rerun the test), thus completing the cycle.

The main challenge here is to restrain yourself from implementing too much. You might have a very precise view from the very beginning about how the FootballTeam class should be implemented. You might be tempted to go ahead and just write it, because you think the code to be written is trivial. The feeling that this is "a piece of cake" that is not worth the trouble of writing tests for is normal. After all, up until now you have been writing code without tests and it has worked pretty well, right? However, I would like to encourage you to follow the test-first pattern, even if it feels a little bit awkward at first. Get to know it, use it for a few hours, and then decide if you like it or not. First impressions might be misleading.

‘The Simplest Thing that Works’ Revisited

Let us take another look at what we did to satisfy the failing test from Listing 4.1. Did we really do the "simplest thing" to make the tests pass? Not really. One could argue that what should have been done is the following:

Listing 4.6. The simplest thing that satisfies the failing test

public class FootballTeam {

public FootballTeam(int gamesWon) {

}

public int getGamesWon() { return 3;

}

}

This snippet of code really does satisfy the failing test. You could call it an absurdity, but there is wisdom in this folly. What it does is prove that your test is not good enough to cover a certain functionality. It says, "Look, your test is so pathetic, that I can make it pass by doing such a silly thing. You need to try harder.". And it really makes you write more tests.

The next test could, for example, be to verify whether the same test passes with a different number of games won – say, 5 instead of 3. Such a test would obviously fail, and then you would have to make the code smarter, so it supports both cases.

52

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