[InternalsVisibleToAttribute] for Unit Testing Private Methods

One of the unit testing challenge developers face is – How to Test a Private Method?

Solution: Use InternalsVisibleToAttribute method in .Net Core

// Enter the Assembly Name of the Unit Test project

// Use internal modifier instead of private

[assembly: InternalsVisibleToAttribute(“UnitTestProject1”)]

namespace ConsoleApp7

{

public class IndustryBL
{
internal int InternalMethod(int x, int y)
{
return x + y;
}
}

}

Now we can Invoke the method from Unit Test.

namespace UnitTestProject1

{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
IndustryBL bl = new IndustryBL();
bl.InternalMethod(2, 3);
}
}

}

Advertisement