unit-testingninjectmoqioc-containerninject-mockingkernel

Why doesn't the following mocking with Ninject.Moq work?


I'm trying to run the following code with Ninject.Moq:

[TestMethod]
public void TestMethod1()
{
    var kernel = new MockingKernel();
    var engine = kernel.Get<ABC>();

   //as I don't need to actually use the interfaces, I don't want
   //to even have to bother about them.

    Assert.AreEqual<string>("abc", engine.ToString());
}

And here is the ABC class definition:

public class ABC {
    IA a;
    IB b;

    public ABC(IA a, IB b)
    {
        this.a = board;
        this.b = war;
    }

    public override string ToString()
    {
        return "abc";
    }
}

I'm getting the following exception:

System.ArgumentException: A matching constructor for the given arguments was not found on the mocked type. ---> System.MissingMethodException: Constructor on type 'AbcProxya759aacd0ed049f3849aaa75e2a7bade' not found.


Solution

  • Ok, this will make the code work:

    [TestMethod]
    public void TestMethod1()
    {
        var kernel = new MockingKernel();
        kernel.Bind<Abc>().ToSelf();
        var engine = kernel.Get<ABC>();
    
       //as I don't need to actually use the interfaces, I don't want
       //to even have to bother about them.
    
        Assert.AreEqual<string>("abc", engine.ToString());
    }
    

    One has to bind Abc to itself, otherwise it will also get mocked and Moq only supports mocking parameterless classes, which is not the case.