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

Chapter 7. Points of Controversy

7.3. Is Set-up the Right Thing for You?

We already know now that it is usually a good thing to make sure that we test a "fresh" SUT and collaborators before putting them through their paces with our test methods. However, this raises the question of how this has been achieved. And this is where some issues arise.

As we already know, JUnit creates a new instance of a test class before each of its methods is executed. This allows us to create the SUT and collaborators in different places. Firstly, we could create the SUT and collaborators along with their declaration as instance members. Secondly, we could create objects within test methods. Thirdly, we could create objects within the specialized set-up methods. Last, but not least, we could combine all of these options. Let us take a closer look at these alternatives.

Listing 7.4. Creation along with declaration

public class DeclarationTest {

Collaborator collaborator = mock(Collaborator.class);

OtherCollaborator otherCollaborator = mock(OtherCollaborator.class);

SUT sut = new SUT(collaborator, otherCollaborator);

@Test

public void testA() { sut.someMethod();

// assertions

}

@Test

public void testB() { sut.otherMethod();

// assertions

}

}

This works fine for "smaller" tests, in which there are not many collaborators and the test fixture is relatively simple. For the creation of more complex objects this technique is less feasible, as the test code becomes less readable.

150

Chapter 7. Points of Controversy

Listing 7.5. SetUp method

public class SetUpTest {

private Collaborator collaborator;

private OtherCollaborator otherCollaborator; private SUT sut;

@Before

public void setUp() {

collaborator = mock(Collaborator.class); otherCollaborator = mock(OtherCollaborator.class); sut = new SUT(collaborator, otherCollaborator);

}

@Test

public void testA() { sut.someMethod();

// assertions

}

@Test

public void testB() { sut.otherMethod();

// assertions

}

}

This might be overkill for simpler tests, but once the number and complexity of the created objects grows, this technique starts to make more sense. Sometimes it is even reasonable to have more than one set-up method, each with an intention-revealing name.

The use of set-up methods for test fixture creation is heavily criticized by some developers. They point out that by removing test fixture creation from the test methods, we make the test methods less readable: i.e. they cannot be understood in isolation – the reader also needs to go through the methods annotated with @Before annotations. No doubt this is something we should be worried about!

151

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