TDD means that we do not write any code without a test, then we move code into internal, private or protected methods as we refactor.
But what if we are writing a method that is to be used by other developers in our development team and it is meant to be an internal class? What happens if we are not using TDD, but have to work on some existing code and need to add a unit test for an internal method?
After having this very issue, it turns out to be much easier to solve than I thought. There is a simple way for us to test internal methods from a separate assembly.
All we have to do is add an attribute into the project we want to test against. Open ‘AssemblyInfo.cs’ from within Properties folder and add the following attribute, replacing ‘MyTestProject with the name of your test assembly:
using System.Runtime.CompilerServices; [assembly:InternalsVisibleTo("MyTestProject")]
As an example, if we have a project called MyProject containing an internal method we want to test and a Test project called MyProject.Tests, we would add the following into AssemblyInfo.cs in the Properties folder of MyProject:
using System.Runtime.CompilerServices; [assembly:InternalsVisibleTo("MyProject.Tests")]
What about security? If we want to make sure that only our tests can use this method, we can wrap the InternalVisibleTo attribute with a Conditional Compilation statement:
using System.Runtime.CompilerServices; #if DEBUG [assembly:InternalsVisibleTo("MyProject.Tests")] #endif