Junit Test Method
I have always a confusion about the Methods in Junit.
If someone is asking whether can I make a test method Private/Protected in Junit, So is he talking about the Method which should start with test or any other method like setup() , teardown() in Junit.
What is the return type of Junit Method. So I have always seen the return type use to be Void so can we change the return type?
Now sometimes the question will come like can I test a Private method Using Junit. So as much I know Junit by default call the method which will start with test and it should be Public then only It will be able to call outside of the class using Junit. So if I declared a test Method as private how Junit will call it or test it outside of the class.
1) Your test methods should be public.
2) return type is always void.
3) You don't test private methods you test the public methods in your class, which will in turn presumably call the logic within your private methods. You should try and cover all the branches of code within these private methods too.
From org.junit.Test annotation docs
The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case
For testing private methods, I recommend making them protected or package protected. Then you can create a subclass that overrides the method and test it.
I have seen many posts stating flatly that you MUST not test private methods. I cannot imagine less useful straitjacketing. If you are trying to refactor your code, you are obligated to yourself and everyone around you to create a set of tests that ensure that the functionality is preserved before you even start changing the code. With regression problems properly fenced in, you can then start refactoring/retesting/refactoring.
Similarly, internal methods often are the places where fault recognition or recovery are done. Testing of those methods requires that proper firewalling of data is performed and that "impossible" situations are recognized. Recovery operations should also be checked to see that they handle "impossible" situations as well.
Using reflection to test private methods is a last resort, but it may be necessary if you cannot change the class under test or if you have orders from management. The "bad practice" is that you are violating encapsulation. However, encapsulation is only of concern to blackbox testing; the process of whitebox testing involves finding out if ALL of your code works, not just the visible stuff.
链接地址: http://www.djcxy.com/p/64104.html上一篇: JUnit android测试classinheritance
下一篇: Junit测试方法