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

Chapter 4. Test Driven Development

As you can see, there are two TDD loops here7. The outer loop relates to working with end-to-end tests in the same test-first manner as we have adopted for unit tests. For example, the outer loop could include tests executed against the GUI, written with the Selenium web testing tool. In order to satisfy such a test, many smaller functionalities must be implemented, which takes us into the inner loop. This, in turn, symbolizes the implementation of unit tests, and pertains to the implementation of much smaller functionalities.

Figure 4.3. TDD on different levels

There is a huge difference between the two loops. A developer will finish many cycles of the inner loop each day, while one cycle of the outer loop might even take him a few days. However, both are identical when it comes to the rhythm of work. In both cases you move from red to green, and then you keep it green while refactoring. This approach to development, based on the TDD method, has also gained a degree of popularity and even has its own name – ATDD, which stands for Acceptance Test Driven Development.

We will not be spending any more time on this broader use of TDD, but after you have mastered TDD at the unit-testing level it is advisable to also try it with different types of test. Once again, [freeman2009] is a must-read.

4.5. Test First Example

Now we are so well educated about test-first, let’s get down to business and do some coding! We shall code a simple class using – surprise, surprise! – the test-first approach.

Take a look at the TDD cycle shown previously. We shall be following its phases one by one. We will start with a failing test. Then, after we have made sure that the error message is informative enough, we will move on to fixing the code. After the test passes we shall concentrate on making the code better by refactoring.

7There might be more of them - i.e. three - if other tests, like integration tests, were also to be taken into account. However, for the sake of simplicity I have decided to put only two of them on the picture.

48

Chapter 4. Test Driven Development

Even though we shall try to follow precisely the steps described in the preceding sections, you will see that in real life some additional work is required. Well, moving from theory to practice is never a painless process.

The example shown in this section is simplified – I realize that. I have made it that simple on purpose, so we can see test-first in practice without being distracted by the complexity of the domain model.

4.5.1. The Problem

Let us play some football, okay? We will implement a FootballTeam class, so we can compare different teams and see who takes first place in the league. Each team keeps a record of the number of games won.

Now we have to think about this. Let us imagine the functionalities of the class and the expected outcomes. All we need is a rough idea, and some guesses regarding the implementation. The details will come later – we do not need to think too hard right now. We should have at least some ideas regarding tests, so we can make the first move. Ok, let us think about this.

So, in our example we have two teams and we need to compare them. It seems like I can use a Comparable interface. Yes, this is a common Java pattern for comparison… no need to think about anything fancy here….Good… Now, if we are to compare them, each team needs to remember the number of games it has won, and the comparison mechanism will use them. So a FootballTeam class needs a field in which to keep this information, and this field should somehow be accessible… Okay… and the most important thing is the comparison…. We need a few tests here: we need to see that teams with more wins are ranked first, and we need to check what happens when two teams have the same number of wins.

— Tomek Dump of a Train of Thought (2011)

All right, I guess this is enough to get us started.

4.5.2. RED - Write a Failing Test

In order to compare two teams, each of them has to remember its number of wins. For the sake of simplicity let us design a FootballTeam class that takes the number of games as a constructor parameter8. First things first: let us make sure that this constructor works.

We start by creating a new class - FootballTeamTest - somewhere in the src/test/java/ directory. It can look like the following:

Listing 4.1. Testing number of games won

public class FootballTeamTest {

@Test

public void constructorShouldSetGamesWon() { FootballTeam team = new FootballTeam(3); assertEquals(3, team.getGamesWon());

}

}

8In a more real-life scenario, a team would probably start with 0 games won, and then, based on the results of games played, it would incrementally adjust its score.

49

Chapter 4. Test Driven Development

Whoa, wait! At this point, your IDE will mark FootballTeam with a red color, as the class does not exist.

Similarly, at this point your IDE will complain about the lack of a getGamesWon() method.

Obviously, you need to create a FootballTeam class and its getGamesWon() method before proceeding any further. You can let your IDE create the class, its constructor and this one method for you, or you can write them yourself.

There are two things to remember when writing code that is necessary in order for a test to compile:

All production code should be kept in a different directory tree from the tests. I suggest following the previously described pattern and putting it in src/main/java.

Do nothing more than the minimum required for the test to compile. Create the necessary classes and methods, but do not fit them out with any business logic. Remember, we want to see our test fail now!

It does not matter whether we created the required code ourselves or let IDE do it (which I recommend): either way, we will end up with an implementation of the FootballTeam class along similar lines to the following:

Listing 4.2. Autogenerated FootballTeam class

public class FootballTeam {

public FootballTeam(int gamesWon) {

}

public int getGamesWon() { return 0;

}

}

It is quite interesting that we get this code "for free". And I am not just referring here to the IDE’s being able to generate it on the basis of the test. Even if we wrote it by hand, it was still hardly an intellectual challenge! Writing the test might have been demanding, but creating the code was very, very simple. That is not always the case, but it does often happen like that.

Since the test compiles, and has an assertion which verifies an important functionality belonging to our class, it is worth running. Once we run it, it fails miserably, with the following message:

Listing 4.3. Failing tests message

java.lang.AssertionError: Expected :3

Actual :0

at org.junit.Assert.fail(Assert.java:93)

at org.junit.Assert.failNotEquals(Assert.java:647) at org.junit.Assert.assertEquals(Assert.java:128) at org.junit.Assert.assertEquals(Assert.java:472) at org.junit.Assert.assertEquals(Assert.java:456) at com.practicalunittesting.FootballTeamTest

.constructorShouldSetGamesWon(FootballTeamTest.java:12)

Let us be clear about this – a failing test at this point is a good thing. Now we know that our test has been executed, and that some important functionality is not ready yet. We will implement it till we see the green light (that is, the test passes).

50

Chapter 4. Test Driven Development

But first, let us resist the urge to fix the code right away. Instead, we should take care of the error message. Does it say precisely what is wrong here? If the answer is "no", then add a custom error message (see Section 8.4). If you are happy with the current message, then proceed further.

Let us say that I have decided that the test will be better if enhanced with the following custom error message:

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

3, team.getGamesWon());

Now, after we have rerun the test, the output will be more informative (stacktrace omitted):

java.lang.AssertionError: 3 games passed to constructor, but 0 were returned

expected: but was:

If we ever break our SUT code, so this test fails, the assertion message will tell us precisely what is wrong and the fix should be easy.

All right then, it is time to move on to the next phase of TDD – we should make the test pass now – by fixing the code, of course.

4.5.3. GREEN - Fix the Code

The fix is straightforward this time: all we need to do is store the value passed as the constructor parameter to some internal variable. The fixed FootballTeam class is presented below.

Listing 4.4. Fixed FootballTeam class

public class FootballTeam { private int gamesWon;

public FootballTeam(int gamesWon) { this.gamesWon = gamesWon;

}

public int getGamesWon() { return gamesWon;

}

}

The test should pass now. However, no celebrations yet! This is the time to polish the code, to refactor and to add comments. No matter how small the changes you have made, rerun the test to make sure that nothing has accidentally been broken.

4.5.4. REFACTOR - Even If Only a Little Bit

In the case of something as simple as this FootballTeam class, I do not see anything worth refactoring. However, let us not forget about the refactoring of the test! The least we should do is to get rid of the magic number 3 – for example, by introducing a THREE_GAMES_WON variable:

51

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