Question

I'm jumping into unit-testing the Visual-Studio 2008 way, and I'm wondering what's the best way to accomplish cross-assembly class access for testing purposes.

Basically, I have two projects in one solution:

  1. MyProject (C#)
  2. MyProjectTests (C# Test Project)

Everything in MyProject currently has default accessibility, which if I recall correctly means everything is effectively internal. I'm mostly looking to test at the class level, but there are a few delegates involved.

There will probably be an external API sometime in the future, but I'm about 20% of the way to feature complete (at least on paper) and I'm getting pretty leery of layering more code on top of this untested core. Accordingly I'd like to get some testing done now, before the app is complete enough for traditional (read: bad and/or lazy) functional testing and definitely before the version n+1 external API is up.

In addition to a straight answer, an example of the solution would be greatly appreciated.

Was it helpful?

Solution

You can use assembly-level attribute InternalsVisibleToAttribute to achieve this.

Add

[assembly:InternalsVisibleTo("MyProjectTests")]

to AssemblyInfo.cs in your MyProject assembly.

OTHER TIPS

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

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

Further info is here

You need to add

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

to AssemblyInfo.cs of your "MyProject (C#)". That then allows your tests to access the internal methods for testing.

Looks like you need the InternalsVisibleToAttribute

However I'd recommend against this approach - test your internal classes via the public interface or API.

Although [InternalsVisibleTo] is most sensible way IMO, there are at least 2 other ways to go about this:

  • By 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 start failing at Run Time, whereas [InternalsVisibleTo] would have easily been picked up this breaking change at compile time.

I found this one https://msdn.microsoft.com/en-us/library/hh598957.aspx Hope it might help someone.

Summary:

  • In your unit test project, add a reference to the code under test. Here’s how to create the reference to a code project in the same solution:
  • Select the project in Solution Explorer.
  • On the Project menu, choose Add Reference....
  • In the Reference Manager dialog box, open the Solution node and choose Projects.
  • Check the code project name and close the dialog box.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top