Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to mock a property with private setter using NSubstitute

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.

like image 892
KDKR Avatar asked Jan 22 '15 22:01

KDKR


People also ask

How do we set a return value for a method call on a substitute?

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.

Which is the basic syntax for creating a substitute?

The basic syntax for creating a substitute is: var substitute = Substitute. For<ISomeInterface>(); This is how you'll normally create substitutes for types.

What is NSubstitute?

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.


1 Answers

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);
}
like image 185
John Koerner Avatar answered Nov 03 '22 10:11

John Koerner