Derik Whittaker



Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at
HowTo: Setting Expectations on Stubs using RhinoMocks

When using a mocking tool like RhinoMocks, one of the features that it can provide is the ability to A) create a stub of an object and B) set expectations on Method/Property calls that are part of that method.  Doing this is pretty easy, but like all things there are some ‘gotcha’s’. 

Below is a step by step on how to set expectations on a stub

  1. Create your mock Repository
    MockRepository mocker = new MockRepository();
  2. Create your stub
    ISomeInterface provider = mocker.Stub< ISomeInterface >();

    Note that I am using the mocker instance NOT MockRepository.GenerateStub.  This is because if you use the static method on the MockRepository object, you WILL NOT have your expectations set in the runtime engine correctly.

  3. Set your expectations
    Expect.Call(provider.SomeMethod(string.Empty, string.Empty)).IgnoreArguments().Return(false);

  4. Set everything in the Mock Engine

  5. Test your stubbed expectation
    bool testValue = provider.SomeMethod();

  6. Check to see if your expectations were met

There you go, you now have a stub with expectations set.

*** Note *** Please pay attention to the fact that if you use MockRepository.GenerateStub your expectation will NOT work correctly.

Till next time,

kick it on

Posted 07-25-2007 7:29 AM by Derik Whittaker



mark.hildreth wrote re: HowTo: Setting Expectations on Stubs using RhinoMocks
on 07-26-2007 7:57 PM

Maybe it's just my whole being new to everything unit-testing, but shouldn't you switch steps #4 & #5? If you call ReplayAll() after you actually test the method, wouldn't the expectation never get satisfied?

Derik Whittaker wrote re: HowTo: Setting Expectations on Stubs using RhinoMocks
on 07-26-2007 8:09 PM


Crap you are right, thanks for that.  I will switch that right now.  

I guess my copy/past from one editor to the other had a bug.  Maybe a unit-test would have found that :)

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Google Reader or Homepage Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of
Red-Gate Tools For SQL and .NET


SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
NHibernate Profiler
Balsamiq Mockups
JetBrains - ReSharper
Web Sequence Diagrams
Ducksboard<-- NEW Friend!


Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers


Community Server (Commercial Edition)