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

Chapter 6. Things You Should Know

separate threads and make them access nextId() in exactly this way – which is by no means easy. JUnit by itself will not help us with this task, but fortunately we can use an external library.

The solution, shown in Listing 6.33, relies on two rules provided by the Tempus-Fugit library18:

ConcurrentRule, which sets the number of threads that are to execute a test method,

RepeatingRule, which sets the total number of test method executions.

There are also two annotations related to these rules: @Concurrent and @Repeating.

Listing 6.33. ID generator tested simultaneously by multiple threads

public class AtomicIdGeneratorParallelTest {

@Rule public ConcurrentRule concurrently = new ConcurrentRule(); @Rule public RepeatingRule repeatedly = new RepeatingRule();

private IdGenerator idGen = new AtomicIdGenerator(); private Set<Long> ids = new HashSet<Long>(100);

@Test @Concurrent(count = 7)

@Repeating(repetition = 100) public void idsShouldBeUnique() {

assertTrue(ids.add(idGen.nextId()));

}

}

Creation of Tempus-Fugit rules: these are required to be marked with the public visibility modifier. The test uses the add() method of the HashSet class, which returns true if, and only if, the element added was not already in the set. In other words, the test will fail if the ID generated is not unique. The idsShouldBeUnique() method will be invoked 100 times, by 7 threads simultaneously. Please note that we need not create any Thread objects in the code. Everything has already been done thanks to the rules of the Tempus-Fugit library.

If you run the test against the AtomicIdGenerator class now, you should see it fail. Apparently, our ID generator is not yet ready to be used by multiple clients at the same time.

6.10.4. Conclusions

Let us leave the implementation of an ID generator as homework for you, dear reader (see Section 6.15.9), and concentrate on the testing side of our example. Here are some comments on what we have seen so far, and also some remarks about further enhancements to the test we have just written.

We have learned that the duo of JUnit and Tempus-Fugit allows us to execute test methods concurrently, through the simple use of annotations. There is no need for you to implement threads yourself. Instead, use the @Concurrent and @Repeating annotations. As the examples here show, this makes the testing code very clean and easy to understand. Definitely a good thing!

6.11. Time is not on Your Side

Time is making fools of us again.

18http://tempusfugitlibrary.org

128

Chapter 6. Things You Should Know

— J.K. Rowling Harry Potter and the Half-Blood Prince (2005)

Alas, after all the years of software development we still cannot get it right! The number of bugs related to time formatting and storage is horrifying. Wikipedia gives a lot of examples of such issues, with the famous Y2K problem among them19. There is definitely something complicated connected with time

– something which makes us write code not in conformity with its quirky and unpredictable nature. In this section we will see how to deal with classes whose behaviour is determined by time.

A typical example of a time-dependent class is shown in Listing 6.34. The code itself is trivial, but testing such code is not.

Listing 6.34. Time-dependent code

public class Hello {

public String sayHello() {

Calendar current = Calendar.getInstance(); if (current.get(Calendar.HOUR_OF_DAY) < 12) {

return "Good Morning!"; } else {

return "Good Afternoon!";

}

}

}

Returns the current date (at the time of the test’s execution).

Please do not be offended by this "HelloWorld" style example. Its point is that it encapsulates everything problematic about the unit testing of time-dependent code. I have seen complicated business code with exactly the same issue as is shown in Listing 6.34. If you learn to solve the problem of Hello class, you will also know how to deal with much more complicated logic.

Whatever test we write in connection with this simple Hello class, its result will depend on the time of execution. An example is shown in Listing 6.35. After execution, one of the tests will fail. This is something we cannot accept. What is expected of unit tests is that they abstract from the environment and make sure that a given class always works.

Listing 6.35. Time-dependent code - a failing test

public class HelloTest {

@Test

public void shouldSayGoodMorningInTheMorning() { Hello hello = new Hello();

assertEquals("Good Morning!", hello.sayHello());

}

@Test

public void shouldSayGoodAfternoonInTheAfternoon() { Hello hello = new Hello();

assertEquals("Good Afternoon!", hello.sayHello());

}

}

19See http://en.wikipedia.org/wiki/Time_formatting_and_storage_bugs

129

Chapter 6. Things You Should Know

One of these assertions will fail.

We need to think of something different… And voila! The trick is to make time a collaborator of the Hello class. In order to do this, we need to:

create a new interface - see Listing 6.36,

redesign Hello class a little bit - see Listing 6.37.

Listing 6.36. The TimeProvider interface

/**

* Allows for taking control over time in unit tests. */

public interface TimeProvider {

Calendar getTime();

}

A default implementation of the TimeProvider interface shown in Listing 6.36 would probably reuse the

system calendar (Calendar.getInstance()).

Listing 6.37. Time as a collaborator

public class HelloRedesigned {

private TimeProvider timeProvider;

public HelloRedesigned(TimeProvider timeProvider) { this.timeProvider = timeProvider;

}

public String sayHello() {

Calendar current = timeProvider.getTime(); if (current.get(Calendar.HOUR_OF_DAY) < 12) {

return "Good Morning!"; } else {

return "Good Afternoon!";

}

}

}

The TimeProvider collaborator has been injected as a constructor parameter, which means it is easily replaceable with a test double.

timeProvider.getTime() is used instead of Calendar.getInstance().

An inquisitive reader may notice that the design of our Hello class can still be improved by moving more functionality into the TimeProvider class. We will address this in one of the exercises at the end of this chapter (see Section 6.15).

Suddenly, the tests of the redesigned Hello class have become trivial.

130

Chapter 6. Things You Should Know

Listing 6.38. Testing time - setting the stage

public class HelloRedesignedTest {

private HelloRedesigned hello; private TimeProvider timeProvider;

@Before

public void setUp() {

timeProvider = mock(TimeProvider.class); hello = new HelloRedesigned(timeProvider);

}

...

}

Here a mock of TimeProvider has been created and injected into the SUT20.

Listing 6.39. Testing time - morning

...

private static final Object[] morningHours() { return $(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);

}

@Test

@Parameters(method = "morningHours")

public void shouldSayGoodMorningInTheMorning(int morningHour) { when(timeProvider.getTime())

.thenReturn(getCalendar(morningHour));

assertEquals("Good Morning!", hello.sayHello());

}

Test methods takes parameters provided by data provider.

Here we have stubbing of the timeProvider test double.

Listing 6.40. Testing time - afternoon

...

private static final Object[] afternoonHours() {

return $(12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23);

}

@Test

@Parameters(method = "afternoonHours")

public void shouldSayGoodAfternoonInTheAfternoon(int afternoonHour) { when(timeProvider.getTime())

.thenReturn(getCalendar(afternoonHour)); assertEquals("Good Afternoon!", hello.sayHello());

}

private Calendar getCalendar(int hour) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY, hour); return cal;

}

}

20Because the test-fixture setting code grew, I decided to put it into a separate method. See Section 7.3 for some discussion.

131

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