Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq'ing an interface

Tags:

c#

.net

tdd

moq

While I'm googling/reading for this answer I thought I would also ask here.

I have a class that is a wrapper for a SDK. The class accepts an ILoader object and uses the ILoader object to create an ISBAObject which is cast into an ISmallBusinessInstance object. I am simply trying to mock this behavior using Moq.

   [TestMethod]
    public void Test_Customer_GetByID()
    {
        var mock = new Mock<ILoader>();

        var sbainst = new Mock<ISbaObjects>();

        mock.Expect(x => x.GetSbaObjects("")).Returns(sbainst);


    }

The compiler error reads: Error 1 The best overloaded method match for 'Moq.Language.IReturns.Returns(Microsoft.BusinessSolutions.SmallBusinessAccounting.Loader.ISbaObjects)' has some invalid arguments

What is going on here? I expected the Mock of ISbaObjects to be able to be returned without a problem.

like image 722
Trevor Abell Avatar asked Dec 23 '22 14:12

Trevor Abell


2 Answers

You need to use sbainst.Object, as sbinst isn't an instance of ISbaObjects - it's just the mock part.

like image 74
Jon Skeet Avatar answered Dec 29 '22 09:12

Jon Skeet


Updated, correct code

[TestMethod]
public void Test_Customer_GetByID()
{
    var mock = new Mock<ILoader>();

    var sbainst = new Mock<ISbaObjects>();

    mock.Expect(x => x.GetSbaObjects("")).Returns(sbainst.Object);


}
like image 45
Trevor Abell Avatar answered Dec 29 '22 10:12

Trevor Abell