Mocking virtual readonly properties with moq

Unit TestingTddMockingMoq

Unit Testing Problem Overview


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

Unit Testing Solutions


Solution 1 - Unit Testing

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

Solution 2 - Unit Testing

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongkdmView Question on Stackoverflow
Solution 1 - Unit TestingMark SeemannView Answer on Stackoverflow
Solution 2 - Unit Testinguser14403065View Answer on Stackoverflow