views:

225

answers:

1

I'm using Moq for unit testing. It order for Moq to work, properties and methodes have to be marked as virtual. Sometimes I pass in data and set property values in the constructors. Isn't there a rule that you should not set virtual properties in constrcutors since it might cause unexpected behaviour (if the class has been inherited from a base class) or is it safe to do it?

+2  A: 

It is, indeed a problem, and Visual Studio Code Analysis explicitly checks for this.

A simple workaround for this is to move the work to a non-virtual internal member, and then have the virtual method call that, as well as the constructor. Something like this:

public class MyClass
{
    public MyClass()
    {
        this.DoStuffInternal();
    }

    public virtual void DoStuff()
    {
        this.DoStuffInternal();
    }

    internal void DoStuffInternal()
    {
        // Interesting stuff happens here
    }
}
Mark Seemann