Добавил:
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.39. No test doubles used

public class ClientTest {

final static String ANY_NUMBER = "999-888-777";

final static Phone MOBILE_PHONE = new Phone(ANY_NUMBER, true); final static Phone STATIONARY_PHONE = new Phone(ANY_NUMBER, false);

Client client = new Client();

@Test

public void shouldReturnTrueIfClientHasMobile() { client.addPhone(MOBILE_PHONE); client.addPhone(STATIONARY_PHONE); assertTrue(client.hasMobile());

}

@Test

public void shouldReturnFalseIfClientHasNoMobile() { client.addPhone(STATIONARY_PHONE); assertFalse(client.hasMobile());

}

}

Real objects are created to be used by the SUT.

Both test methods use real objects of the Phone class, and both rely on its correctness.

The test code shown in Listing 5.39 is clear and concise. The required DOCs are created using a Phone class constructor with the appropriate boolean parameter - true for mobiles and false for stationary phones.

5.5.2. Using Test Doubles

The alternative approach would be to use test doubles instead of real objects. This is shown in Listing 5.40.

Listing 5.40. Test doubles

public class ClientTest {

final static Phone MOBILE_PHONE = mock(Phone.class); final static Phone STATIONARY_PHONE = mock(Phone.class);

Client client = new Client();

@Test

public void shouldReturnTrueIfClientHasMobile() { when(MOBILE_PHONE.isMobile()).thenReturn(true);

client.addPhone(MOBILE_PHONE); client.addPhone(STATIONARY_PHONE); assertTrue(client.hasMobile());

}

@Test

public void shouldReturnFalseIfClientHasNoMobile() { client.addPhone(STATIONARY_PHONE); assertFalse(client.hasMobile());

}

}

Collaborators are created using Mockito’s mock() method. The creation of DOCs is completely independent from constructor(s) of the Phone class.

91

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