[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);
}
}

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s