8

With NSubstitute, is there any way to capture the value you pass to a property setter?

E.g. if I have the following interface:

public interface IStudent {
    int Id { set; }
    string Name { set; }
}

The say I have a substitute created e.g:

var _studentSub = Substitute.For<IStudent>();

Is there any way I can intercept and capture the value if any of the "set" methods of the substitute are invoked?

Petter Hesselberg
  • 5,062
  • 2
  • 24
  • 42
bstack
  • 2,466
  • 3
  • 25
  • 38

1 Answers1

17

The standard approach for NSubstitute is to have properties with getters and setters, as then properties on substitutes will work as expected (i.e. you'll get back what is set).

If your interface has to have setter-only properties you can capture the value of an individual property using Arg.Do:

[Test]
public void Setter() {
    var sub = Substitute.For<IStudent>();
    var name = "";
    sub.Name = Arg.Do<string>(x => name = x);

    sub.Name = "Jane";

    Assert.AreEqual("Jane", name);
}
David Tchepak
  • 9,826
  • 2
  • 56
  • 68
  • For a property with get/set, Can you use sub.Name = Arg.Do(x => name = x); to capture a value and still use sub.Name.Returns("MySampleName"); for returning values? The 'returns' does not seem to work for us! – bstack Oct 05 '11 at 07:52
  • 1
    Just checked, seems to be a bug mixing Arg.Do and Returns for the same get/set property. It works if you switch Arg.Do for When..Do. e.g. "sub.When(x => x.Name = Arg.Any()).Do(x => name = x.Arg());" – David Tchepak Oct 05 '11 at 21:41
  • 1
    See [bug report](https://github.com/nsubstitute/NSubstitute/issues/59) for working When..Do example. – David Tchepak Oct 05 '11 at 22:00
  • [Bug](https://github.com/nsubstitute/NSubstitute/issues/59) should now be fixed in latest builds. – David Tchepak Oct 10 '11 at 12:37
  • The accepted solution does not appear to work in v2.0.2. – sixeyes Apr 12 '17 at 11:04
  • @sixeyes: just tested against v2.0.2 and it worked ok. Can you post a repro somewhere? Here's the version I ran: https://gist.github.com/dtchepak/59d48169b500b4f43fba85a5e1bb1403 – David Tchepak Apr 12 '17 at 22:46
  • My apologies. I pasted the code above into my test project and it didn't work. I've just tried your code and it works. There must be something fishy with my configuration – sixeyes Apr 13 '17 at 08:32