I understand that @VisibleForTesting is not desirable because it changes the interface of a class just for testing purposes. Ideally we should test the interface that we actually use. But what would be a good alternative?
Asked
Active
Viewed 1.7k times
24
-
Feel free to post the code to [CodeReview.SE](http://codereview.stackexchange.com/). – palacsint Dec 22 '11 at 10:34
-
I really meant as a general question, as opposed to a specific piece of code needing refactoring. – Thiago Dec 22 '11 at 12:45
1 Answers
42
You use @VisibleForTesting
when, as you said, you want to test a part of code you're not exposing to the end user. If you want to test it then it most likely means it's complicated, or at least not trivial. Two solutions would be:
- Split the method where you're calling this into several methods so you feel more comfortable about not having one big method doing a bunch of stuff at once.
- See if you can move the behavior to an external object that takes care of it.
I like #2 a lot when stuff starts getting complicated, since I can have an external object that I can test and make sure it works without having to expose it through our interface.
Having said that, some times the behaviors don't warrant the extraction of the method into a new object and you use @VisibleForTesting
just to save time. Experience is what tells you when it's worth it to do it (or not).

Federico Builes
- 4,939
- 4
- 34
- 48
-
13+1 for moving to an external object. This is one of those win-win situations where writing good tests actually improves the code you're testing. – millhouse Dec 22 '11 at 03:28
-
1This answer does not address the case when you have to add additional modifier methods to a class in order to make it configurable for testing. This occurs in particular in conjunction with dependency injection, when your production code uses @Autowired to wire dependencies, where as the test code needs to problematically set them separately in each test method of the respective unit test to test different scenarios. – Fritz Duchardt Apr 02 '15 at 16:15