C# – use Moq to set values for fields

cmockingmoqnet

I have a dependency that I would like to mock.

public abstract class MyDependency
{
    protected Dictionary<string, object> _outputs = new Dictionary<string, object>();
    public Dictionary<string, object> Outputs
    {
        get
        {
            return _outputs;
        }
    }
}

I need the public property Outputs to return a known value for the purpose of my unit test. I know that we cannot mock fields or non-virtual members. So, I could go and create my own mocked MyDependency that sets the backing field _outputs:

public class MockMyDependency : MyDependency
{
    public MockMyDependency()
    {
        _outputs = new Dictionary<string, object>
        {
            { "key", "value" }
        };
    }
}

However, is it possible to use Moq to do this without explicitly creating my own derived mock class?

Best Answer

If you cannot change the property to be virtual or define an interface (I assume if you can't do the first one you won't be able to do the second one either) then I see only two possible options:

  • Use a mocking framework that does support mocking of non virtual members (e.g. TypeMock)
  • Create a specific mock implementation that inherits from MyDependency as you already did.
Related Topic