Friday, July 21, 2017

Unit Testing internal methods in c#



Sometimes you want to unit test private or protected methods on a class in one of your assemblies (MyAssembly). The problem is the unit test assembly (MyAssembly.Tests) is just another assembly and has to respect the access modifiers such as private, protected, public, internal, etc.

I generally subscribe to the notion that if you have a private method there is a good chance you should be moving that functionality to another class and using dependency injection to make that logic public and testable.

There are however exceptions to this such as when overriding a protected or protected method for example. While the same principle could be applied, it may or may not be the best choice. For cases where you deem it to not the best choice there is a solution.

In your assembly (of the class you are testing) you can add the following to the AssemblyInfo.cs file to grant special rights to any class (our unit test assembly in this case) such that it has access to internal (sorry private, protected, etc still can't) methods and thus allowing you to test them.

[assembly: InternalsVisibleTo("MyAssembly.Tests")]

If you really need to test private methods you can use PrivateObject to invoke the private method in your unit test. This feels a bit dirty though.

4 comments:

mahalyasree said...

It’s the best time to make some plans for the future and it is time to be happy. I’ve read this post and if I could I want to suggest you few interesting things or suggestions.You can write next articles referring to this article. I desire to read even more things about it..
Office Interior Designers in Bangalore
Office Interior Designers in Hyderabad

Unknown said...

Thanks for spending your valuable time in delivering the most valuable content here.I loved the way you write and suggest my friends too for getting aware of your blogs.
Installment Loans
Installment Loans in Alabama
Installment Loans in Mississipi
Installment Loans in South Carolina

melinamia said...

I’m really amazed with your posting skills as well as with the layout on your blog site. Is this a paid style or did you modify it yourself? Either way keep up the pleasant quality writing, it is rare to see a great site such as this one these days.
Delivery service singapore
Singapore delivery service
24 hour delivery singapore

The India said...


san diego seo expert

seo company in india