Same setup for many properties in Moq I'm trying to use Moq to mock a rather large set of interfaces in an object. I'm trying to capture the behavior of retaining a dirty flag when properties are set and I'm hoping there is a cleaner way to do this because I have many properties that need this setup.

    public static void SetupDirtyProperty&lt;T, TProp&gt;(this Mock&lt;T&gt; mock, Expression&lt;Func&lt;T, TProp&gt;&gt; getterExpression, Action&lt;T&gt; setterExpression, ref bool isDirty)
    {
        TProp p = default(TProp);

        mock.SetupGet(getterExpression).Returns(() =&gt; p);
        mock.SetupSet(setterExpression).Callback((TProp value) =&gt;
        {
            if (p != value)
            {
                p = value;
                isDirty = true;
            }
        });
    }


and to use it it's called like this:

        bool isDirty = false;
        var product = new Mock&lt;IProduct&gt;();

        product.As&lt;ISku&gt;().SetupDirtyProperty(x =&gt; x.Price, x =&gt; x.Price= It.IsAny&lt;decimal?&gt;(), () =&gt; isDirty = true);


The things I would like to simplify about this approach are:


I have to specify a property getter and setter, but it seems like I should be able to invert the property getter expression into a setter with It.IsAny&lt;TProp&gt; that will work correctly with Moq.
I have to specify the closure around the isDirty flag every time.


It'd be nice if I could set this up in a way that is easy to apply this to dozens of properties, and it'd be really nice if it was something like SetupAllProperties where it would just handle all the properties automatically.
Keeping code DRY is a noble goal, even for test code, but it's less important for tests. Our first priority when writing test code is being precise and clear. The tests are the specs and the specs are the tests. It's important that it be immediately clear what the state of the mocked object is. We can expect to duplicate a certain amount of code. 

Looking at your test, in isolation from your extension, it's difficult to tell exactly what is going on here. 


bool isDirty = false;
var product = new Mock&lt;IProduct&gt;();

product.As&lt;ISku&gt;().SetupDirtyProperty(x =&gt; x.Price, x =&gt; x.Price= It.IsAny&lt;decimal?&gt;(), () =&gt; isDirty = true);



If you need to create this same Moq for many tests, it would be better to use the [TestInitialize] attribute and have it set up prior to each test method being run. See this for more information.