How to mock a function call on a concrete object with Moq?

You should use Moq to create your Mock object and set CallBase property to true to use the object behavior.

From the Moq documentation:
CallBase is defined as “Invoke base class implementation if no expectation overrides the member. This is called “Partial Mock”. It allows to mock certain part of a class without having to mock everything.

Sample code:

    [Test]
    public void FailintgTest()
    {
        var mock = new Moq.Mock<MyClass>();
        mock.Setup(m => m.Number).Returns(4);
        var testObject = mock.Object;
        Assert.That(testObject.Number, Is.EqualTo(4));
        Assert.That(testObject.Name, Is.EqualTo("MyClass"));
    }

    [Test]
    public void OKTest()
    {
        var mock = new Moq.Mock<MyClass>();
        mock.Setup(m => m.Number).Returns(4);
        mock.CallBase = true;
        var testObject = mock.Object;
        Assert.That(testObject.Number, Is.EqualTo(4));
        Assert.That(testObject.Name, Is.EqualTo("MyClass"));
    }

    public class MyClass
    {
        public virtual string Name { get { return "MyClass"; } }

        public virtual int Number { get { return 2; } }
    }

Leave a Comment