164

We put all of our unit tests in their own projects. We find that we have to make certain classes public instead of internal just for the unit tests. Is there anyway to avoid having to do this. What are the memory implication by making classes public instead of sealed?

1

6 Answers 6

241

If you're using .NET, the InternalsVisibleTo assembly attribute allows you to create "friend" assemblies. These are specific strongly named assemblies that are allowed to access internal classes and members of the other assembly.

Note, this should be used with discretion as it tightly couples the involved assemblies. A common use for InternalsVisibleTo is for unit testing projects. It's probably not a good choice for use in your actual application assemblies, for the reason stated above.

Example:

[assembly: InternalsVisibleTo("NameAssemblyYouWantToPermitAccess")]
namespace NameOfYourNameSpace
{
7
  • 25
    I'd suggest putting a #if DEBUG around the attribute, and then unit testing in debug. That way you'll be sure that the attribute isnt set on release code.
    – steve cook
    Jul 2, 2013 at 3:47
  • 10
    Well, why limiting tests to debug builds ?
    – Marco Mp
    Mar 23, 2015 at 9:53
  • 2
    Also, just a nitpick, there's no need for the "friend" assemblies to be strongly named (might be a good practice - even if my personal taste says otherwise, but not mandatory).
    – Marco Mp
    Mar 23, 2015 at 9:56
  • 9
    Disagree. If I'm building a complex component with a very thin public API, it's unpractical and unrealistic to only test through the public API. You'll end up with an unmaintainble ball of mud. Instead, I'd carefully define the internal units and testing them separately. As Jeremy D. Miller has said quite often: "Test small before you test big". Jun 12, 2015 at 10:55
  • 5
    For .NET Core - add InternalsVisibleTo to any .cs file in the app. See details here - stackoverflow.com/a/42235577/968003
    – Alex Klaus
    Nov 2, 2017 at 1:14
19

Below are ways to use in .NET Core applications.

  1. Add AssemblyInfo.cs file and add [assembly: InternalsVisibleTo("AssemblytoVisible")]
  2. Add this in .csproj file (the project which contains the Internal classes)
<ItemGroup>
  <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
    <_Parameter1>Test_Project_Name</_Parameter1> <!-- The name of the project that you want the Internal class to be visible To it -->
  </AssemblyAttribute>
</ItemGroup>

For more information please follow https://improveandrepeat.com/2019/12/how-to-test-your-internal-classes-in-c/

4

If it is an internal class then it must not be getting used in isolation. Therefore you shouldn't really be testing it apart from testing some other class that makes use of that object internally.

Just as you shouldn't test private members of a class, you shouldn't be testing internal classes of a DLL. Those classes are implementation details of some publicly accessible class, and therefore should be well exercised through other unit tests.

The idea is that you only want to test the behavior of a class because if you test internal implementation details then your tests will be brittle. You should be able to change the implementation details of any class without breaking all your tests.

If you find that you really need to test that class, then you might want to reexamine why that class is internal in the first place.

10
  • 2
    Implementation details should be exercised as part of a encompassing test. Don't peek at private variables... test expected behavior. If the test is right.. all the internal plumbing and wiring should be tested as part of it. Voted up.
    – Gishu
    Sep 20, 2008 at 5:52
  • 78
    i dont necessarily agree with this as these classes are "public" to other classes inside the DLL and the functionality of the class should be tested indepdently
    – leora
    Sep 20, 2008 at 15:36
  • 33
    I also don't agree. Units are units and they must be tested in isolation.
    – Sentinel
    Nov 10, 2011 at 10:00
  • 5
    Great general guideline, but let's not get dogmatic. Tests serve two main purposes: 1) Regression - make sure you didn't break something, 2) Increasing the speed of development. If I have to stand up a huge service every time I want to write a line of code I will be hampering development. If I have a complex internal piece I want to be able to develop and test in isolation. Conversely, I don't want everything tested in isolation (thus decreasing regression testing value, or duplicating test code), but some code justifies isolation. Perhaps the key is to make it a separate assembly.
    – Lee Jensen
    Jan 6, 2015 at 16:18
  • 2
    OP here is correct. You're coupling your tests to the internal implementation. Hence your team is forever a slave to mending the tests and horrible mocking code. Test public APIs only, be that packaged lib API or network exposed APIs. All code should be exercisable via the front door. Testing implementation is why TDD has largely died, it's just a huge PITA to test literally every class of the whole app, rather than focus on assuring behaviours of the system. I think almost everyone, including "authoritative" books, have had this wrong or not made it clear. Oct 15, 2018 at 13:59
4

for documentation purposes

alternatively you can instantiate internal class by using Type.GetType method

example

//IServiceWrapper is public class which is 
//the same assembly with the internal class 
var asm = typeof(IServiceWrapper).Assembly;
//Namespace.ServiceWrapper is internal
var type = asm.GetType("Namespace.ServiceWrapper");
return (IServiceWrapper<T>)Activator
    .CreateInstance(type, new object[1] { /*constructor parameter*/ });

for generic type there are different process as bellow:

var asm = typeof(IServiceWrapper).Assembly;
//note the name Namespace.ServiceWrapper`1
//this is for calling Namespace.ServiceWrapper<>
var type = asm.GetType("Namespace.ServiceWrapper`1");
var genType = type.MakeGenericType(new Type[1] { typeof(T) });
return (IServiceWrapper<T>)Activator
     .CreateInstance(genType, new object[1] { /*constructor parameter*/});
0

We are in 2023 now and this is now possible with dotnet 8 using UnsafeAccessorAttribute. Before dotnet 8 the solution was either to use the internal keyword (that does not answer the question because internal is different that private) Or using reflection wich is very slow. Now in dotnet 8 you can access private fields without having to use reflection:

https://www.meziantou.net/accessing-private-members-without-reflection-in-csharp.htm

-6

Classes can be both public AND sealed.

But, don't do that.

You can create a tool to reflect over internal classes, and emit a new class that accesses everything via reflection. MSTest does that.

Edit: I mean, if you don't want to include -any- testing stuff in your original assembly; this also works if the members are private.

2
  • 1
    Wait, what? You're saying don't make a public sealed class? What's your reasoning for that gem?
    – crush
    Oct 29, 2015 at 2:36
  • @crush traumapony has not logged in since 2009. Jun 26, 2019 at 15:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.