30 August 2013

Allowing .Net unit tests to access internal members

Good code encapsulation requires that various members be marked as private, or at least internal. However this can make it difficult for unit test frameworks such as NUnit to access them.

You can grant an external (e.g. unit test) assembly access to internal members by doing the following:

  1. Give your test assembly a strong name (via Project Properties, Signing, Sign the assembly)
  2. Compile the assembly (eg. My.Test.dll)
  3. Open the Visual Studio command prompt
  4. Navigate to the folder where My.Test.dll got built
  5. Run:  sn -Tp My.Test.dll
  6. This will display the full public key for the signed assembly. Copy it. (it'll be about 320 chars)
  7. Open the AssemblyInfo.cs file for the assembly containing the code with internals to be tested.
  8. Enter a line such as: [assembly: InternalsVisibleTo("My.Test, PublicKey=1234")] where 1234 is the full key generated in step 6.
Note: this only works if the full key is used, not the shorter summary key.

No comments: