Search code examples
c#unit-testingninjectrhino-mocks

What is the proper way to use the Ninject RhinoMocksMockingKernel to test a class that has two constructor arguments of the same type?


I am testing a class that has two dependencies on IFoo. Both instances of IFoo should be MOCK objects so that I can VerifyExpectations on each. Each instance is created and managed by the RhinoMocksMockingKernel.

I think that the mocking kernel is getting confused about which instance it should be verifying.

I also think that I may be confused about the proper way to setup RhinoMocksMockingKernel for this case.

I do know that I can use dep1.AssertWasCalled... vs. dep1.VerifyAllExpectations().

Here is the sample code.

public interface IFoo
{
    void DoX();
    void DoY();
}

public class SubjectUnderTest
{

    private readonly IFoo dep1;
    private readonly IFoo dep2;

    public void DoWork()
    {
        dep1.DoX();
        dep2.DoY();
    }

    public SubjectUnderTest(IFoo dep1, IFoo dep2)
    {
        this.dep2 = dep2;
        this.dep1 = dep1;            
    }
}

[TestFixture]
public class Tests
{
    [Test]
    public void DoWork_DoesX_And_DoesY()
    {
        var kernel = new Ninject.MockingKernel.RhinoMock.RhinoMocksMockingKernel();
        var dep1 = kernel.Get<IFoo>();
        var dep2 = kernel.Get<IFoo>();

        // tried this binding but it doesnt seem to work
        kernel.Bind<SubjectUnderTest>()
            .ToSelf()
            .WithConstructorArgument("dep1", dep1)
            .WithConstructorArgument("dep2", dep2);

        var sut = kernel.Get<SubjectUnderTest>();

        dep1.Expect(it => it.DoX());
        dep2.Expect(it => it.DoY());

        sut.DoWork();

        dep1.VerifyAllExpectations();
        dep2.VerifyAllExpectations();
    }
}

Solution

  • So I found a way to verify the expections on dep1 and dep2, but I was not able to use the AutoMockingKernel to manage and create dep1 and dep1.

    Here is the code that I came up with.

    It's pretty lame answer. It seems like I should be able to use the mocking kernel to Get two seperate instances of IFoo...

    Here is my current code... lameo...

    [TestFixture]
    public class Tests
    {
        [Test]
        public void DoWork_DoesX_And_DoesY()
        {
            var kernel = new Ninject.MockingKernel.RhinoMock.RhinoMocksMockingKernel();
            var dep1 = MockRepository.GenerateMock<IFoo>();
            var dep2 = MockRepository.GenerateMock<IFoo>();
    
            kernel.Bind<IFoo>().ToMethod((ctx) => dep1).When((ctx) => ctx.Target.Name.StartsWith("dep1"));
            kernel.Bind<IFoo>().ToMethod((ctx) => dep2).When((ctx) => ctx.Target.Name.StartsWith("dep2"));
    
            var sut = kernel.Get<SubjectUnderTest>();
    
            dep1.Expect(it => it.DoX());
            dep2.Expect(it => it.DoY());
    
            sut.DoWork();
    
            dep1.VerifyAllExpectations();
            dep2.VerifyAllExpectations();
        }
    }