moq Mocking properties Properties with private setters


Sometimes you want to create a mock of a class that has a private setter:

public class MockTarget
    public virtual string PropertyToMock { get; private set; }

Or an interface that only defines a getter:

public interface MockTarget
    string PropertyToMock { get; }

In both cases, you can ignore the setter and simply Setup the property getter to return a desired value:

var mock = new Mock<MockTarget>();
mock.SetupGet(x => x.PropertyToMock).Returns("ExpectedValue");

Assert.AreEqual("ExpectedValue", mock.Object.PropertyToMock);