I am having a problem with "xxxx is inaccessible due to its protection level". I have read a lot of manuals how to test classes with internal access. I have inserted
[assembly: System.Runtime.CompilerServices.InternalsVisibleToAttribute("UnitTests, PublicKey=mykey")]
in ProjectA into a class which I want to test. And in my TestProject I have also added a reference to ProjectA. Both have the same *.snk. But it keeps throwing the error.
Some suggestions?
Without seeing your specific class, it's hard to be precise, but ensure the following:
internal
or public
internal
InternalsVisibleTo
property contains the full namespace of your test project.i.e. if your test project is MyProject.UnitTests
, then you need to have that in your InternalsVisibleTo
, e.g.:
[assembly: System.Runtime.CompilerServices.InternalsVisibleToAttribute("MyProject.UnitTests")]
I've never used the PublicKey part of the InternalsVisibleTo
, so I can't comment on that, but you could try removing it. Usually works without it for me.
[assembly: System.Runtime.CompilerServices.InternalsVisibleToAttribute("MyProject.UnitTests")]
Public Key Value
Assuming those are all fine, and it's still not working, I would guess it's something to do with the PublicKey value you are entering. At a quick web search, it appears that you don't enter the key name, but the key value. To get that, follow this Set of instructions to get that value. I'll quote the instructions here for posterity.
The InternalsVisibleTo Attribute can be used to allow another assembly (such as your Unit Test assembly) to see the internal members of your assembly. I prefer this method to either putting unit tests in my primary assembly or to using the VSTS feature of autogenerating accessors to my private members. (Those are real fun when you go to refactor a project…)
Now most of the info you will find about this refers to the earlier beta usage. The attribute used to take in a PublicKeyToken but now takes in a PublicKey.
To use the InternalsVisibleTo Attribute:
- Run sn.exe -p MyStrongNameKey.snk MyStrongNameKey.PublicKey
This will extract to public key to a file with the .PublicKey extension. (I hate using the .pub extension because it is seen as a Microsoft Publisher file…)
- run sn.exe -tp MyStrongNameKey.PublicKey
This will display your public key for you. Copy this key.
Create an attribute as such:
[assembly: InternalsVisibleTo( "MyProject.UnitTests, PublicKey=PASTE-YOUR-PUBLIC-KEY-HERE" )]
Note that the public key that was displayed was 5 lines or so. Remove the line breaks from the public key and paste it into your attribute.
You are done! The assembly MyProject.UnitTests can now see the internal members of your assembly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With