3

Unfortunately the following pattern does not work in RhinoMocks:

[SetUp]
public void SetUp ()
{
    obj.Stub(s => s.Prop).Returns("a suitable default for all tests");
}

[Test]
public void VerySpecificTest ()
{
    obj.Stub(s => s.Prop).Returns("specific value, valid only for this single test");
}

It does not even throw an exception (which is particularly bad), the user just does not know why the second Stub() call does not have any effect whatsoever.

However, is there a way to make this work? How to "overwrite" a single property return?

D.R.
  • 20,268
  • 21
  • 102
  • 205

1 Answers1

3

IIRC, the supported way to override a previously recorded behavior of a stub or mock is to fall back Rhino Mocks' older API: you can use BackToRecord to cause the stub to forget its previously recorded behavior, then use Replay to go back to playback mode, then stub the property again:

[SetUp]
public void SetUp ()
{
    obj.Stub(s => s.Prop).Returns("a suitable default for all tests");
}

[Test]
public void VerySpecificTest ()
{
    // Clear recorded expectations and immediately go back to replay mode.
    obj.BackToRecord();
    obj.Replay();

    // Now setup a new expectation.
    obj.Stub(s => s.Prop).Returns("specific value, valid only for this single test");
}

The drawback to this method is that BackToRecord causes the stub to forget all the expectations set up for it (not only the one you might want to override). There are a few hackarounds that avoid this (e.g., to use Repeat, or to set up the initial Stub using a lambda so that you can change the returned value later on; see e.g., How to clear previous expectations on an object? for some of these), but there is no supported API for this.

Community
  • 1
  • 1
Fabian Schmied
  • 3,885
  • 3
  • 30
  • 49
  • Your explanation of `BackToRecord` sounds like all my Stub() calls are gone? So it's kinda like creating a new stub from scratch? – D.R. Oct 28 '14 at 12:54
  • Yes, and it also changes the stub's behavior to behave like a strict mock, so ... not quite ideal. – Fabian Schmied Oct 28 '14 at 14:14
  • This is a good answer to a similar question: http://stackoverflow.com/a/770083/62838. – Fabian Schmied Oct 28 '14 at 14:15
  • There is one more twist to it: when put the `Stub` call between `BackToRecord` and `Replay`, it switches the object to strict mode. When, however, you put the `Stub` call _after_ the `Replay`, it keeps the stub behavior. I'll adapt the code sample accordingly. – Fabian Schmied Oct 28 '14 at 14:21
  • Thanks for all the information, I've found the other thread before as well, however, I thought there must be some easy/easier way to achieve this... :-) – D.R. Oct 28 '14 at 16:49
  • I've edited the answer to contain all the additional details :) – Fabian Schmied Oct 29 '14 at 07:12