Alternatives to @VisibleForTesting

Thiago picture Thiago · Dec 22, 2011 · Viewed 15.9k times · Source

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?

Answer

Federico Builes picture Federico Builes · Dec 22, 2011

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:

  1. 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.
  2. 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).