Alternatives to @VisibleForTesting

蹲街弑〆低调 提交于 2019-12-20 09:49:26

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/8599023/alternatives-to-visiblefortesting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!