how to mock a property with private setter using NSubstitute

KDKR picture KDKR · Jan 22, 2015 · Viewed 11.5k times · Source

I am having a class "Example" with a property "data" which has a private setter and I would like to mock that data property

Public class Example { public string data {get; private set;}}

I would like to mock the data property using NSubstitute. Could someone help me how to do it.

Answer

John Koerner picture John Koerner · Jan 22, 2015

NSubstitute can only mock abstract or virtual methods on concrete classes. If you can modify the underlying code to use an interface , then you could mock the interface:

public class Example : IExample { public string data { get; private set; } }
public interface IExample { string data { get; } }

[TestMethod]
public void One()
{
    var fakeExample = NSubstitute.Substitute.For<IExample>();
    fakeExample.data.Returns("FooBar");

    Assert.AreEqual("FooBar", fakeExample.data);
}