5

Suppose, that I've got a following class:

public abstract class Test
{
    internal abstract int Prop 
    {
        get;
    }
}

Now, I try to make a mock using NSubstitute:

var mock = Substitute.For<Test>();

But that fails:

Method 'get_Prop' in type 'Castle.Proxies.TestProxy' from assembly 'DynamicProxyGenAssembly2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=a621a9e7e5c32e69' does not have an implementation.

I thought of adding NSubstitute to [InternalsVisibleTo], but unfortunately my tested assembly is signed, NSubstitute is not and Internals cannot be VisibleTo unsigned class.

How can I solve this problem?

Spook
  • 25,318
  • 18
  • 90
  • 167

2 Answers2

10

I've found the solution. One has to add the following line to the Assembly.cs file of the assembly, he wants to test (not the test assembly):

[assembly:InternalsVisibleTo("DynamicProxyGenAssembly2")]
Spook
  • 25,318
  • 18
  • 90
  • 167
  • Which public key are you using there? Is it a constant? – justin.m.chase Feb 10 '14 at 21:47
  • It was some time ago, but AFAIR this is a public key extracted from NSubstitute assemblies (there's a way to do this with tools available with Visual Studio). – Spook Feb 11 '14 at 06:43
  • Yeah it appears to be constant. I pasted this into my assemblyinfo.cs and it worked as is. – justin.m.chase Feb 12 '14 at 04:46
  • 7
    Use [assembly: InternalsVisibleTo(InternalsVisible.ToDynamicProxyGenAssembly2)] instead – Austin Salgat Jul 27 '17 at 20:53
  • @Austin Salgat I think you meant [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] – Arialdo Martini Mar 21 '23 at 17:28
  • Edited to account for no need for the public key. – Spook Mar 23 '23 at 09:00
  • @ArialdoMartini The Castle.Core assembly has a class InternalsVisible under the Castle.Core.Internal namespace meant for this specific use. The documentation states: `// Constant to use when making assembly internals visible to proxy types generated by DynamicProxy. Required when proxying internal types. [assembly: InternalsVisibleTo(CoreInternalsVisible.ToDynamicProxyGenAssembly2)]` – Austin Salgat Mar 28 '23 at 04:42
0

The voted answer does not work anymore.

Use the following instead. Either add this to any .cs file in your project:

[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]

or this, to the .csproj file of the Project:

<ItemGroup>
    <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
        <_Parameter1>DynamicProxyGenAssembly2</_Parameter1>
    </AssemblyAttribute>
</ItemGroup>
Arialdo Martini
  • 4,427
  • 3
  • 31
  • 42