ninject / Ninject.MockingKernel

Extension for Ninject aiding testability in Moq, NSubstitute, and FakeItEasy
http://ninject.org/
Other
62 stars 25 forks source link

Test passes with StandardKernel, but Fails With MockingKernel #26

Closed gfeld closed 6 years ago

gfeld commented 8 years ago

In the following example the test passes when using StandardKernel and fails with MoqMockingKernel
namespace ClassLibrary4 { using Ninject; using Ninject.MockingKernel.Moq; using System; using Xunit;

    public class Foo
    {
        public Foo([Target1]Bar bar1, [Target2]Bar bar2)
        {
            this.bar1 = bar1;
            this.bar2 = bar2;
        }

        public Bar bar1 { get; private set; }
        public Bar bar2 { get; private set; }
    }

    public class Bar
    {
        public Bar(IZed zed) { this.zed = zed; }
        public IZed zed { get; private set; }
    }

    public interface IZed { }

    public class Zed1 : IZed { }

    public class Zed2 : IZed { }

    public class Target1 : Attribute { }
    public class Target2 : Attribute { }

    public class Tests
    {
        [Fact]
        public void Pass()
        {
            var kernel = new StandardKernel();
            kernel.Bind<IZed>().To<Zed1>().WhenAnyAncestorMatches(r => r.Request.Target?.IsDefined(typeof(Target1), true) ?? false);
            kernel.Bind<IZed>().To<Zed2>().WhenAnyAncestorMatches(r => r.Request.Target?.IsDefined(typeof(Target2), true) ?? false);

            var foo = kernel.Get<Foo>();
            Assert.IsType<Zed1>(foo.bar1.zed);
            Assert.IsType<Zed2>(foo.bar2.zed);
        }

        [Fact]
        public void Fail()
        {
            var kernel = new MoqMockingKernel();
            kernel.Bind<IZed>().To<Zed1>().WhenAnyAncestorMatches(r => r.Request.Target?.IsDefined(typeof(Target1), true) ?? false);
            kernel.Bind<IZed>().To<Zed2>().WhenAnyAncestorMatches(r => r.Request.Target?.IsDefined(typeof(Target2), true) ?? false);

            var foo = kernel.Get<Foo>();
            Assert.IsType<Zed1>(foo.bar1.zed);
            Assert.IsType<Zed2>(foo.bar2.zed);
        }
    }
}
scott-xu commented 6 years ago

The MockingKernel will bind Bar as singleton. This is by design. You can abstract Bar with an interface IBar.