๐ซ Avoid Making Methods Public Just for Unit Testing
Making methods Public solely for the sake of unit testing is not considered a best practice. Here's why and what you should do instead.
โ Why It's Not Best Practice?
- ๐ Encapsulation\ Exposing internal implementation details breaks encapsulation, leading to misuse and tight coupling.
- ๐งฉ API Pollution\ Expanding the public surface area makes your class harder to maintain and understand.
- ๐งผ Design Smell\ If you feel the need to test internals, it might be a sign that your class is doing too much or needs refactoring.
โ
Recommended Alternatives
1๏ธโฃ Test via the Public Methods
๐งช Instead of testing private methods directly, test through public methods that use them.
๐ Example:\ Rather than testing a private FormatData() method, test the public Export() method that internally calls it.
2๏ธโฃ Refactor for Testability
๐ ๏ธ If a method is complex and needs direct testing, consider extracting it into a separate class or helper.
This allows it to be.
- โ
Tested independently
- โ
Appropriately exposed
- โ
Better organized for maintainability
3๏ธโฃ Use Friend (VB.NET) or internal (C#) with InternalsVisibleTo
๐ง In VB.NET, mark methods as Friend and use.
<Assembly: InternalsVisibleTo("YourTestAssembly")>
๐ง In C#, mark methods as internal and add to your .csproj or AssemblyInfo.cs.
[assembly: InternalsVisibleTo("YourTestAssembly")]
This allows your test project to access internal members without making them public.