Search code examples
visual-studioresharperrhino-mocks

Resharper challenge: Using .Mock().Return() instead of setters and vice versa


I often have a problem related to the way Rhino Mocks forces you to use setters when they are available, instead of mocking (and vice versa).

For example:

var foo = MockRepository.GenerateStub<IFoo>();

// Valid only if Bar has a setter (of course, otherwise it wouldn't compile)
foo.Bar = new Bar(); 

// Valid only if Bar does not have a setter (less obvious, as this will compile)
foo.Stub(x => x.Bar).Return(new Bar());

Dealing with these can be a real hassle, especially when doing refactoring.

So my question is, can anyone think of a good way to customize a Resharper/Visual Studio shortcut that would allow me to quickly convert from one to the other?


Solution

  • Answering my own question - a custom inspection pattern can help with this.

    The search pattern is: $object$.$property$ = $value$;

    The replace pattern is: $object$.Stub(x => x.$property$).Return($value$);

    $object$ and $value$ are both expression placeholders, and $property$ is an identifier placeholder.

    Unfortunately, because this as a Code Inspection it is visible all the time, causing green squiggles to appear throughout the code base.