InternalsVisibleTo does not work

I insert the line:

[assembly: InternalsVisibleTo("MyTests")]

inside my project under test( Properties/AssemblyInfo.cs) where MyTests is the name of the Unit Test project. But for some reason I still cannot access the internal methods from the unit test project.

Any ideas about what I am doing wrong ?

4

7 Answers

If your assembly is signed with a strong name look at this answer.

Otherwise check that the name of your test assembly really is "MyTests.dll" (it doesn't have to match the project name, though it will by default).

3

Let's break it down a bit as many of us have experienced this slight mix-up in the past...

Assembly A has your internal class. Assembly B has your unit tests.

You wish to grant the internals of assembly A visibility in assembly B.

You need to put the InternalsVisibleTo assembly attribute inside assembly A and grant access to assembly B.

0

I had the same issue after renaming a namespace. Basically the in .cs files was the new namespace but in the .csproj and AssemblyInfo.cs it was the old namespace.

namespace newNamespace { .... } 

So, I changed in .csproj the following to the new namespace:

 <RootNamespace>oldnamespace</RootNamespace> <AssemblyName>oldnamespace</AssemblyName> 

And in AssemblyInfo.cs:

[assembly: AssemblyTitle("oldnamespace")] [assembly: AssemblyProduct("oldnamespace")] 

You still need your test project to reference your main project.

This can be easy to overlook and if you have no existing test code this may appear like the InternalsVisibleTo is not functioning.

In my case I was coding to an Interface. As interfaces can only specify public properties the internal properties were not present on the interface.

Make sure you're not doing the same thing as I was!

I changed:

Assert.IsNotNull((exportFileManager)?.ThumbnailFileExporter); 

To:

Assert.IsNotNull((exportFileManager as ExportFileManager)?.ThumbnailFileExporter); 
3

I made the incorrect assumption that InternalsVisibleTo will help in accessing Private methods too.

Here are some other aspects that can lead to this error:

  • Your class is either internal or public
  • Your method is internal
  • The InternalsVisibleTo property contains the full namespace of your test project.
3

You can expose internals from strong named assembly to another strong named friend assembly only. But non-strong named assembly can expose internals to strong named friend assembly.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like