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

Chapter 7. Points of Controversy

Access Modifiers

Another option we have is to weaken the access modifier of a private method – something which will make it more easily accessible by test code. However, we do not usually want to make such a method public. Adding new methods to the API of a class, just because we want to test it, would be too much. Fortunately, we can achieve our goal by relaxing the access modifier just a little. This is shown in Listing 7.12.

Listing 7.12. Testing private methods by relaxing access modifiers

public class SomeClass {

boolean privateMethod(Long param) { return true;

}

}

public class PrivateMethodAccessModifierTest {

@Test

public void testingPrivateMethodWithReflection() { SomeClass sut = new SomeClass(); assertTrue(sut.privateMethod(9238423L));

}

}

privateMethod() is no longer private - it has a "default" access modifier, which means it can be called directly from classes within the same package.

This solution requires a serious change in the production code, which might not be possible. On the other hand, the test code is "normal" - that is, free from any unexpected constructs. It is also immune to name changes of tested methods, as refactoring tools will easily update the new method name within the test code.

7.5.4. Conclusions

When writing the section on private methods testing, I must confess I was in two minds as to whether I should describe this at all. One part of me argued that it is evil and anti-OO, and that I should not include it in a book that sets out to promote good practice, and that puts a lot of pressure on one with respect to the quality of one’s code. The other part of me argued that I should have faith in my readers. My role will be to present and describe the different options so that you, dear reader, can decide by yourself which way to go. So it looks as though, in the end, this second part of me must have prevailed!

I have tried very hard to discourage you from testing private methods. I still think that with good design, you will never need to test them directly. However, I do think that sometimes (very rarely, but still…) you might need to use the techniques described in this section. This is why I have decided to include them in the book.

A note on tools. The authors of some tools - e.g. TestNG or JUnit - have never got around to enhancing their tools in order to make them capable of testing private methods - even though there have been some expectations on the part of community members that they would do so. This is probably because they view private methods testing as something that does not deserve to be facilitated.

159

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