.NET  

Don't Make public just for writing Unit Test

๐Ÿšซ 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.