0

I have a class

public class MyClass
{
   public int MyProperty1 { get; private set; }
   public int MyProperty2 { get; private set; }

   public MyClass(){}
   public MyClass(int myProperty2) => MyProperty2 = myProperty2;
}

in my unit tests i need to change the value of MyProperty1 before making my assertion like below

[Fact]
public void MyTest()
{
   var fake = NSubstitute.Substitute.For<MyClass>(3);
   fake.MyProperty1.Returns(5);

   //Assertion
}

However I am getting the error

Outcome: Failed
    Error Message:
    NSubstitute.Exceptions.CouldNotSetReturnDueToNoLastCallException : Could not find a call to return from.

David Tchepak
  • 9,826
  • 2
  • 56
  • 68
Chitova263
  • 719
  • 4
  • 13
  • This might be an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). My first question is why are you trying to do that? What are you actually trying to test? – Nkosi Dec 10 '19 at 00:55

1 Answers1

0

NSubstitute can not stub non-virtual members of classes (see How NSubstitute Works for an explanation). I strongly recommend adding the NSubstitute.Analyzers package to any test project that references NSubstitute, as this will provide compile-time warnings when an attempt is made to substitute a non-virtual method.

With Property1 updated to virtual the test works as expected:

public class MyClass
{
    public virtual int MyProperty1 { get; private set; }
    public int MyProperty2 { get; private set; }

    public MyClass() { }
    public MyClass(int myProperty2) => MyProperty2 = myProperty2;
}
David Tchepak
  • 9,826
  • 2
  • 56
  • 68