Mocking virtual readonly properties with moq

gkdm picture gkdm · Sep 21, 2009 · Viewed 17k times · Source

I couldn't find a way to do this, though this can be done by hand so why not with moq?

Answer

Mark Seemann picture Mark Seemann · Sep 21, 2009

Given this class

public abstract class MyAbstraction
{
    public virtual string Foo
    {
        get { return "foo"; }
    }
}

you can set up Foo (a read-only property) like this:

var stub = new Mock<MyAbstraction>();
stub.SetupGet(x => x.Foo).Returns("bar");

stub.Object.Foo will now return "bar" instead of "foo".