How to access classes in another assembly for unit testing purposes?

I am transitioning to unit testing of Visual-Studio 2008, and I am wondering what is the best way to cross-build a class for testing.

Basically, I have two projects in one solution:

  • MyProject (C #)
  • MyProjectTests (C # Testing Project)

Everything in MyProject currently has default access, which, if I remember correctly, means that everything is effectively internal . I mainly try to test the class level, but there are several delegates .

There will probably be an external API in the future, but I will be about 20% of how you can complete the full one (at least on paper), and I get quite a few questions laying over more code on top of this unchecked kernel. Accordingly, I would like to conduct some testing before the application is sufficiently complete for the traditional (read: bad and / or lazy) functional testing and, of course, before the release of the external API version n + 1.

In addition to the direct answer, an example solution would be very helpful.

+16
c # .net-assembly unit-testing
Jul 31 '09 at 9:59
source share
5 answers

To achieve this, you can use the assembly level attribute InternalsVisibleToAttribute .

Add

 [assembly:InternalsVisibleTo("MyProjectTests")] 

in AssemblyInfo.cs in your MyProject assembly.

+28
Jul 31 '09 at 10:02
source share

You need to add

 [assembly:InternalsVisibleTo("Unit.Tests.Assembly")] 

in AssemblyInfo.cs of your "MyProject (C #)". This allows your tests to access internal testing methods.

+3
Jul 31 '09 at 10:03
source share

You can test internal methods by adding an attribute to AssemblyInfo.cs for your main project, providing access to internal methods for a named assembly:

[assembly: InternalsVisibleTo ("MyProjectTestsNameSpace.MyProjectTests")]

More info here

+3
Jul 31. '09 at 10:04
source share

Looks like you need InternalsVisibleToAttribute

However, I would recommend against this approach - to test your inner classes through an open interface or API.

+1
Jul 31 '09 at 10:04
source share

Although [InternalsVisibleTo] is the most sensible IMO way, there are at least two other ways to do this:

  • Using Reflection

      var method = instance.GetType().GetMethod( methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, paramTypeArray, null); return method.Invoke(instance, parameters); 

The problem with this approach is that if the method name or signature changes, the unit test will crash at runtime, while [InternalsVisibleTo] easily catch this violation at compile time.

0
Nov 07 '13 at 12:23
source share



All Articles