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.
To set a return value for a method call on a substitute, call the method as normal, then follow it with a call to NSubstitute's Returns() extension method. var calculator = Substitute. For<ICalculator>(); calculator.
The basic syntax for creating a substitute is: var substitute = Substitute. For<ISomeInterface>(); This is how you'll normally create substitutes for types.
NSubstitute is a friendly substitute for . NET mocking libraries. It has a simple, succinct syntax to help developers write clearer tests. NSubstitute is designed for Arrange-Act-Assert (AAA) testing and with Test Driven Development (TDD) in mind.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With