gkdm
gkdm

Reputation: 2375

Mocking virtual readonly properties with moq

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

Upvotes: 60

Views: 23448

Answers (2)

user14403065
user14403065

Reputation: 21

You need to make sure property is virtual to make this work.

Upvotes: 2

Mark Seemann
Mark Seemann

Reputation: 233477

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".

Upvotes: 101

Related Questions