14

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.

KDKR
  • 365
  • 2
  • 3
  • 11
  • 1
    Likely not possible - most mocking libraries are not able to mock non-virtual, non-interface methods. Short of redesigning your classes you'll need some much heavier tool that can rewrite code like [Microsoft Moles](https://msdn.microsoft.com/en-us/library/ff798308.aspx). – Alexei Levenkov Jan 22 '15 at 22:38
  • It might be worth noting whether you are able to edit the `Example` class. As noted by @AlexeiLevenkov, if you can't then NSub can't help you. If you can, @JohnKoerner's answer shows one way to do it. – David Tchepak Jan 23 '15 at 02:33
  • Place the getter procedure in a `virtual` method and then mock that. –  Sep 06 '21 at 12:15

1 Answers1

19

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);
}
John Koerner
  • 37,428
  • 8
  • 84
  • 134
  • Making `Example.data` virtual would also work for this test without adding the interface. (Although I generally prefer interfaces for dynamic proxy-based mocking.) – David Tchepak Jan 23 '15 at 02:29
  • Sounds correct, but I've been able to use substitute.Received(1).Method() where Method is not abstract or virtual. – Frank Schwieterman Oct 18 '16 at 00:07