Changing private methods to protected for testing

喜你入骨 提交于 2019-12-22 04:12:27

问题


Is it a good idea to change the private methods to protected for JUNIT testing.?


回答1:


It's sometimes useful, yes.

If the class is extendable, make sure to make the method final.

Also, document the fact that the method is not supposed to be called by subclasses or external classes of the same package.

I use the Guava @VisibleForTesting annotation to make it clear that the method should in fact be private.




回答2:


No in general not. The idea of unit testing is to test ... units. Or in other words implementations of interface methods. If you want to test a method which you can't "see" this could be a code smell. Maybe you haven't separated your business logic enough from the UI code or something.

So the best idea would be to rethink your architecture. But if the alternative would be to not test your code it is a good idea to make those methods protected.




回答3:


You can make the methods package local instead.

You can call private method using reflection, or you can decide that private methods shouldn't be tested directly, only indirectly.




回答4:


Although you should prefer to refactor as @user714965 suggested, PowerMock's MockPrivate can do the mocking without opening the visibility of your private methods.

Writing your tests first usually leads to a design where you don't need to mock private methods.



来源:https://stackoverflow.com/questions/10141626/changing-private-methods-to-protected-for-testing

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