🚫 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.

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.

VB.NET
<Assembly: InternalsVisibleTo("YourTestAssembly")>

🔧 In C#, mark methods as internal and add to your .csproj or AssemblyInfo.cs.

C#
[assembly: InternalsVisibleTo("YourTestAssembly")]

This allows your test project to access internal members without making them public.