Unit Testing a class with an internal constructor

Viewed 11918

I have a class called "Session" which exposes several public methods. I'd like to Unit Test these, however in production I need to control instantiation of "Session" objects, so delegate construction to to a SessionManager class and have made the Session's constructor internal.

I'd ideally like to test the Session class in isolation from the SessionManager which creates it/them to prove that the public interfaces exposed by the Session work as expected - but can't instantiate a Session from a test without using a SessionManager making my tests more complicated/less useful than they need to be.

What's the best way to deal with this?

Cheers,

Lenny.

7 Answers

For .Net Core you can modify .csproj

...
<ItemGroup>
    <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
        <_Parameter1>$(AssemblyName).Tests</_Parameter1>
    </AssemblyAttribute>
</ItemGroup>
...

It will make internal stuff visible for your test project.

Related