Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternatives to @VisibleForTesting

Tags:

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?

like image 533
Thiago Avatar asked Dec 22 '11 03:12

Thiago


1 Answers

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

like image 162
Federico Builes Avatar answered Sep 21 '22 17:09

Federico Builes