C# – How to use moq to test a concrete method in an abstract class

abstract classcmockingmoqunit testing

In the past when I wanted to mock an abstract class I'd simply create a mocked class in code that extended the abstract class, then used that class in my unit testing…

public abstract class MyConverter : IValueConverter
{
    public abstract Object Convert(...);

    public virtual Object ConvertBack(...) { ... }
}

private sealed class MockedConverter : MyConverter { ... }

[TestMethod]
public void TestMethod1()
{
    var mock = new MockedConverter();

    var expected = ...;
    var actual = mock.ConvertBack(...);

    Assert.AreEqual(expected, actual);
}

I want to get into the habit of using Moq instead. I'm not sure how I'd go about using Moq to test the default return value of my abstract class. Any advice here?

Best Answer

If you set CallBase to true, it will invoke the base class implementation.

var mock = new Mock<MyConverter> { CallBase = true };

See the Customizing Mock Behavior Customizing Mock Behaviour section of the Quick Start.

Invoke base class implementation if no expectation overrides the member (a.k.a. "Partial Mocks" in Rhino Mocks): default is false.