Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migration of unmigrated content due to installation of a new plugin

Since testing classes in isolation is a good thing it is sometimes nice to be able to
have a quick dummy implementation of an interface without having to instantiate the object (and
needing a reference to a concrete class). Why mocking is good can be found in many posts (see gennaGena's post here http://wiki.deltares.nl/pages/viewpage.action?pageId=5272)

This is a quick how-to stub with RhinoMocks.

What is stubbing? Stubbing is quickly creating dummy instances of interfaces. Stubs are not used to test behaviour (calls on objects). Mocks are used for that.

This is a quick how-to stub with RhinoMocks. It is meant as a reference. When you want something stubbed-out in your test and don't know the syntax it might be here (hopefully (wink) . In that .

Without further redo a few handy usages :

it would be nice to expand this post.

Setting it up.

To stub you need a mockrepository. Set it up some where in your (test)class:

Code Block

        private static readonly MockRepository mocks = new MockRepository();

Properties with getter/setter

...

Unfortunately our syntax gets more complex and we need to turn on the stub using
mocks.ReplayAll();

Mocking void methods

Methods without return values are easy. You get default implementation doing nothing (smile)

...

Code Block
        var mock = mocks.Stub<IInterface>();
        mock.Stub(a => a.GetMyString(null)).IgnoreArguments().Return("kees");
        mocks.ReplayAll();

Returning based on input

Code Block
        mock.Stub(a => a.GetMyString("rock")).IgnoreArguments().Return("paper");
        mock.Stub(a => a.GetMyString("paper")).IgnoreArguments().Return("scissor");
        mocks.ReplayAll();

Resulting in rock->paper and paper->scissor

Helping the mock object out of its verified state

Suppose you have the System.InvalidOperationException: This action is invalid when the mock object is in verified state
You can't use a mock in Rhino Mocks after its expectations were verified, even if you're calling a method that does not make part of your expectations.
To solve this use the following:

Code Block

[TearDown]
        public void TearDown()
        {
            mocks.BackToRecordAll();
            if (testee != null)
                testee.Dispose();
        }

        [Test]
        public void Test()
        {
            // Expectations setup
            someInterface.DoStuff();
            mocks.ReplayAll();

            // Replay
            testee.SomeInterface = _someInterface;
            testee.DoSomeOtherStuff();
            mocks.VerifyAll();
        }