Alternatives to @VisibleForTesting

前端 未结 1 1210
轮回少年
轮回少年 2021-02-01 17:50

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 actuall

相关标签:
1条回答
  • 2021-02-01 18:20

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

    0 讨论(0)
提交回复
热议问题