0

I have some code, like:

class MyClass
{
    private int _myField;

    public int MyField => _myField;
}

How can I mock up MyField using nsubstitute? Or it's impossible?

Shadr
  • 214
  • 1
  • 12

2 Answers2

4

For NSubstitute to be able to mock your property, it must be virtual or abstract. But after that, you can mock it just like anything else:

var mock = Substitute.For<MyClass>();
mock.MyField.Returns(-1);
germi
  • 4,628
  • 1
  • 21
  • 38
1

More commonly you would want to be substituting a value on an interface. Now if your MyClass implemented the ITest interface below you would be able to just substitute on the interface.

[Test]
public void CanSubstituteReadOnlyPropertyOnInterface()
{

  var n = NSubstitute.Substitute.For<ITest>();
  n.X.Returns(55);
  Assert.AreEqual(55, n.X);

}

public interface ITest
{
    int X { get; }

}
Andrew
  • 5,215
  • 1
  • 23
  • 42