Home > Software design >  Methods to be only available in Unit test
Methods to be only available in Unit test

Time:10-28

I'm looking for a way to make methods only available in Unit test scripts.

public class MyClass
{
    public Data MyData { get; }
    internal MyClass()
    {
        // Complex code setting MyData
    }
#if UNITY_MACROS
    public MyClass(MyData data)
    {
         MyData = data;
    }
#endif
}

The need is that the public constructor would only be available in the Unit Test scripts and assembly.

I tried to look into Define constraints in the Test assembly but I am probably not using right since I don't see any difference.

CodePudding user response:

What you need is to use the InternalsVisibleTo attribute (MS docs). You can add the following line either in your class source file, or in a separate AssemblyInfo.cs which you can create in the same folder as your asmdef file:

[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("MyUnitTestAssembly")]

In that case you can leave MyClass(MyData data) internal.

  • Related