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

Chapter 5. Mocks, Stubs, Test Spies

Listing 5.28. setUp() method introduced

public class RaceResultsServiceFirstAndSecondRefactoredTest {

private RaceResultsService raceResults = new RaceResultsService(); private Message message = mock(Message.class);

private Client clientA = mock(Client.class, "clientA"); private Client clientB = mock(Client.class, "clientB");

@Test

public void subscribedClientShouldReceiveMessage() { raceResults.addSubscriber(clientA); raceResults.send(message);

verify(clientA).receive(message);

}

@Test

public void allSubscribedClientsShouldReceiveMessages() { raceResults.addSubscriber(clientA); raceResults.addSubscriber(clientB); raceResults.send(message);

verify(clientA).receive(message); verify(clientB).receive(message);

}

}

Now the test methods are much thinner and the creation code is not repeated.

5.4.3. The Third Test: Send Messages to Subscribers Only

The next step is to make sure that clients who are not subscribed do not receive any messages. Looking at the code written so far, I suspect the test will pass instantly; still, it needs to be tested (so that later on, if some changes are made to the code, this functionality will not be broken). The implementation of such a test method is shown in Listing 5.29.

Listing 5.29. The third test: clients not subscribed do not receive any messages

public void notSubscribedClientShouldNotReceiveMessage() { raceResults.send(message);

verify(clientA, never()).receive(message); verify(clientB, never()).receive(message);

}

This test presents a new feature of Mockito: its ability to check that something has not occurred. This is done using the static never() method. As usual with Mockito, the code is very readable ("verify that clientA has never received a message").

As expected, the new test passes instantly.

The fact that the last test passed instantly should make us feel just a little uneasy. This is a warning sign. It might mean that the test repeats what other tests have already

84

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