NSubstitute icon indicating copy to clipboard operation
NSubstitute copied to clipboard

Implement get and set at once for property values.

Open smaudet opened this issue 4 years ago • 0 comments

For the following interface:

public interface IInterfaceUnderTest
{
    bool PublicProperty { get; set; }
}

The following test code works.

interfaceUnderTest.PublicProperty = Arg.Do<bool>(x => propertyValue = x);
interfaceUnderTest.PublicProperty = true;
interfaceUnderTest.PublicProperty.Returns(callInfo => propertyValue);

Assert.AreEqual(true, propertyValue);
Assert.AreEqual(true, interfaceUnderTest.PublicProperty);

The following does not:

interfaceUnderTest.PublicProperty = true;
interfaceUnderTest.PublicProperty = Arg.Do<bool>(x => propertyValue = x);
Assert.AreEqual(true, interfaceUnderTest.PublicProperty);
interfaceUnderTest.PublicProperty.Returns(callInfo => propertyValue);
Assert.AreEqual(true, interfaceUnderTest.PublicProperty);

The first succeeds because the property is set after the set is in place, the second does not because the previous value is overwritten by the Arg.Do call. In this case, one could simply set propertyVaue, the proposed feature is to assign both in one call e.g.:

interfaceUnderTest.PublicProperty = Arg.DoAndReturn<bool>(x => {val}, () =>val)
// or
interfaceUnderTest.PublicProperty.DoAndReturn<bool>(x => {val}, () =>val)

This would eliminate some confusion when a property is set and get with some custom simulated behavior.

smaudet avatar Oct 14 '21 02:10 smaudet