2

I discovered an odd anomaly with NSubstitute class instantiation. Working with Sitecore 8.1 update 3 Sitecore.Kernell.dll, the following test passes:

[Fact]
public void CanCreateSubstituteDatabase()
{
  Database db = Substitute.For<Sitecore.Data.Database>("sub");
  db.Should().NotBeNull();
}

This despite the fact that there is only an internal constructor for Sitecore.Data.Database:

 internal Database(string name)
 {....

I have confirmed that this is not normal behavior for NSubstitute. I created a project "ExternalLibrary" with this code:

namespace ExternalLibrary
{
    public class Foo
    {
        internal Foo(string bar)
        {
            Bar = bar;
        }

        public string Bar { get; }
    }
}

When I try to use NSubstitute to instantiate this in a separate library,

namespace NSubClassInstantiation
{
    using ExternalLibrary;
    using FluentAssertions;
    using NSubstitute;
    using Xunit;

    public class FooTest
    {
        [Fact]
        public void CanInstantiate()
        {
            var foo = Substitute.For<Foo>("baz");

            foo.Bar.Should().Be("baz");
        }
    }
}

the test fails as expected with the following exception,

System.NotSupportedException: Parent does not have a default constructor. The default constructor must be explicitly defined.

Why is this error not thrown with the Sitecore.Data.Database class?

Gatogordo
  • 2,629
  • 2
  • 22
  • 32
Dan Solovay
  • 3,134
  • 3
  • 26
  • 55

1 Answers1

2

NSubstitute namespace is marked InternalsVisibleTo in Sitecore.Kernel.

What is the DynamicProxyGenAssembly2 assembly?

From Sitecore.Kernel: [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]

Community
  • 1
  • 1
Mark Cassidy
  • 5,829
  • 1
  • 22
  • 33
  • Bam, that was quick. :D – Dan Solovay Aug 13 '16 at 15:29
  • Haha. Only because I'd been studying Sitecore.Kernel attributes closely, quite recently ;-) – Mark Cassidy Aug 13 '16 at 15:30
  • Of course, this means an Evil Implementer can do an end-run around the constructor, and use SubstituteForPartsOf to make their own DBs. ;) – Dan Solovay Aug 13 '16 at 15:34
  • I've named Test projects "Sitecore.IntegrationTests" in the past ;-) As for evil - how about: https://github.com/cassidydotdk/Sitecore.Datalift/blob/master/src/Sitecore.Datalift.Tests/SitecoreFaker.cs – Mark Cassidy Aug 13 '16 at 15:37
  • Double clicking on the assembly in DotPeek or ReSharper AssemblyExplorer shows the Assembly properties, including the line Mark included above. See http://stackoverflow.com/questions/28700047/how-can-i-check-for-an-internalsvisibleto-attribute-on-an-assembly – Dan Solovay Aug 13 '16 at 15:42