C#: Testing the internals of another project

2021.01.04 | 265 words |

Overview

Any project of sufficient size will eventually need testing. In dotnet land this usually involves creating a separate project for your tests like MyProjectTests. Many tests may want to test internal functions - like say an internal calculation or hash. However doing this right out of the box will leave you with an error like this:

error CS0117: 'MyClass' does not contain a definition for 'MyInternalElement'

Here I’ll share how to make your project MyProject share its internals with your project’s tests MyProjectTests.

Solution

The problem here is that our standard visibility rules (like internal) are preventing our test from reading in these elements. Generally this is good, we mark things with visibility rules to prevent others from accessing things we don’t think they should be accessing. In our case it’s bad because we do want to access them for a good cause - testing that they work.

So to make this happen we can employ a strategy where we make the namespace of MyProject reveal its internal visibility elements to our namespace of MyProjectTests. Note that this may change depending on how you set up your namespaces.

To do this we can use the assembly attribute with InternalsVisibleTo MyProjectTests on our MyProject namespace. This comes out to something like this:

using System;
using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("MyProjectTests")]
namespace MyProject
{
    ...
}

Now you should be able to access elements marked as internal from your testing project.

One extra thing to call out is you’ll likely need to add using System.Runtime.CompilerServices; to your code as well so your project knows what that attribute is.

 

About the Ham

Hi I'm Hamilton - I built this! If you want more content like this subscribe to my email list, connect with me around the web, or take a look at some of my other projects.

More Projects

comments powered by Disqus