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?
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?
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);
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; }
}