如何使用NSubstitute模拟私有setter的属性

KDK*_*DKR 7 c# private nsubstitute

我有一个类"示例",其属性"data"具有私有setter,我想模拟该数据属性

Public class Example { public string data {get; private set;}}
Run Code Online (Sandbox Code Playgroud)

我想使用NSubstitute来模拟数据属性.有人可以帮我怎么做.

Joh*_*ner 16

NSubstitute只能在具体类上进行模拟abstractvirtual方法.如果您可以修改底层代码以使用接口,那么您可以模拟接口:

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);
}
Run Code Online (Sandbox Code Playgroud)