C# - VS 2010 Unit Testing for private methods
VS 2010 allows for private method uni开发者_如何学编程t testing. Is that a good idea? I have always heard that unit testing scenarios were for the public methods only. Should I bother with the private methods and properties?
Thanks Leo
In his infinite wisdom, Jon Skeet once wrote (in C# in depth) 'I’m happy to test whatever I can in the simplest manner possible'
IMHO, if you think a private method deserves unit testing then test it.
Two reasons to not test private methods:
1) Brittle tests. Private method is an implementation detail that you might want to change it in future without breaking tests.
2) Duplication. Code in private methods should be covered by the tests that exercise object using its public interface. If this is the case than you would simply be testing the same thing twice.
Although it would be nice to test all of your private methods/properties too, what really counts are your public methods/properties (i.e. what you expose to the outside world). Ultimately, your private methods/properties will be used somehow by your public methods/properties.
If you want to test your private methods/properties on their own, then test them. But since they will not be used directly (and instead, indirectly), I don't feel it is absolutely necessary.
As it has been said, test it if you feel the need and you are able to, but be aware that a unit test of a private method is more likely to be broken if someone modifies it, which can become a great pain in the ass in a big project with a lot of unit tests, my advice would be, test only those methods whose functionality are very clear and more unlikely to be changed.
精彩评论