Ayende @ Wiki

Edit

A "fluent" way of expectation specifying and verifying

An alternative way of specifying expectations for a block of code to be verified, is the With class. It provides some kind of fluent interface and is a little bit more compact than the Rhino Mocks Record-playback Syntax, but comes with the drawback of using anonymous delegates.

// Prepare mock repository
MockRepository mocks = new MockRepository();
IDependency dependency = mocks.CreateMock<IDependency>();

object result;

With.Mocks( mocks ).Expecting( delegate { // Record expectations Expect.Call( dependency.SomeMethod() ).Return( null ); }) .Verify(delegate { // Replay and validate interaction IComponent underTest = new ComponentImplementation( dependency ); result = underTest.TestMethod(); });

// Post-interaction assertions Assert.IsNull( result );


ReplayAll() and VerifyAll() are implicitly called, when executing the code passed in as anonymous delegates. To take care of the order of expectations, ExpectingInSameOrder() can be used:

// Prepare mock repository
MockRepository mocks = new MockRepository();
IDependency dependency = mocks.CreateMock<IDependency>();
IAnotherDependency anotherDependency = mocks.CreateMock<IAnotherDependency>();

object result;

With.Mocks( mocks ).ExpectingInSameOrder( delegate { // Record expectations which must be met in the exact same order Expect.Call( dependency.SomeMethod() ).Return( null ); anotherDependency.SomeOtherMethod(); }) .Verify(delegate { // Replay and validate interaction IComponent underTest = new ComponentImplementation( dependency, anotherDependency ); result = underTest.TestMethod(); });

// Post-interaction assertions Assert.IsNull( result );


Edit

A wrapper to ensurer VerifyAll()



This kind of syntax allows the MockRepository to be created on the fly and automatically call VerifyAll() at the end. The MockRepository is accessible through the static property Mocker.Current.

   With.Mocks(delegate
   {
        IDemo demo = Mocker.Current.CreateMock<IDemo>();
        Expect.Call(demo.ReturnIntNoArgs()).Return(5);
        Mocker.Current.ReplayAll();
        Assert.AreEqual(5, demo.ReturnIntNoArgs());
    });


Instead of implicitly creating a new one, a specific MockRepository can be used too:

   MockRepository mocks = new MockRepository();
   With.Mocks(mocks, delegate
   {
        IDemo demo = Mocker.Current.CreateMock<IDemo>();
        Expect.Call(demo.ReturnIntNoArgs()).Return(5);
        Mocker.Current.ReplayAll();
        Assert.AreEqual(5, demo.ReturnIntNoArgs());
    });


When using Mocker.Current, be aware, that you can't use the above syntax in nested constructs, because the global Mocker.Current will be override with each With.Mocks() call.

Up: Rhino Mocks Documentation
Next: Rhino Mocks Limitations

ScrewTurn Wiki version 2.0 Beta. Some of the icons created by FamFamFam.