Chris Covert
Chris Covert

Reputation: 2834

Ninject Extension Factory with Moq

I've been using Ninject for dependency injection and inversion of control, and I have been using Moq for testing purposes quite successfully; however, I recently came into a position in which I needed to start using the factory extension of Ninject.

I have code along the lines of:

interface IBarFactory
{
    Bar CreateBar();
}

class Bar : IBar
{
    ...
}

class BarModule
{
    public override void Load()
    {
        Bind<IBarFactory>().ToFactory();
    }
}

class Tests
{
    [Fact]
    public void TestMethod()
    {
        var bar = new Mock<IBar>();
        bar.Setup(b => b.DoSomething())
            .Verifiable();

        var barFactory = new Mock<IBarFactory>();
        cryptoKeyFactoryMock.Setup(f => f.CreateBar())
            .Returns(bar.Object)
            .Verifiable();

        var someOtherClass = new SomeOtherClass(barFactory.Object);
    }
}

When attempting to force the IBarFactory mock to return an IBar mocked object, I get an error due to the fact that the CreateBar() method expects a Bar typed object rather than an IBar typed one.

Has anyone had more success using Moq with Ninject Factory?

Upvotes: 0

Views: 451

Answers (1)

Steve Py
Steve Py

Reputation: 34783

I don't think the issue is Ninject specifically, but just that you seem to be declaring an Interface solely for testing. Is there a reason that the BarFactory shouldn't return IBar?

Moq can mock classes, not just interfaces. You can set up a Mock<Bar> instance for the mocked BarFactory call to return. The caveat is that any methods/properties you want to assert on the Mocked Bar instance must be declared as virtual. So in your example, if you declare DoSomething() as virtual then you can set up a mock of type Bar with your declaration instead of IBar.

Upvotes: 3

Related Questions