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:
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.
You can use assembly-level attribute InternalsVisibleToAttribute to achieve this.
Add
[assembly:InternalsVisibleTo("MyProjectTests")]
to AssemblyInfo.cs in your MyProject assembly.
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.
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
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.
Moles / Fakes
or TypeMock
I found this one https://msdn.microsoft.com/en-us/library/hh598957.aspx Hope it might help someone.
Summary:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.