C#: Testing the internals of another project
Date: 2021-01-04 | csharp | testing |
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.
Want more like this?
The best / easiest way to support my work is by subscribing for future updates and sharing with your network.