You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 12 Next »

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 genna'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.

Without further redo a few handy usages :

Properties with getter/setter

        interface IInterface
        {
            string Name{ get;set; }
        }

Can be used directly since the default property behaviour of stubs gives us a getter setter

        var mock = mocks.Stub<IInterface>();
        mock.Name = "lee";

Readonly properties

Given an interface with a readonly property:

        interface IInterface
        {
            string ReadOnly { get; }
        }

We can use it like this in test

        var mock = mocks.Stub<IInterface>();
        mock.Stub(a => a.ReadOnly).Return("kees");
        mocks.ReplayAll();//don't forget or you will get null

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)

        interface IInterface
        {
            void Go();
        }

We can use it like this in test

        var mock = mocks.Stub<IInterface>();
        mock.Go();

Mocking method with return values

What if you need a method to return a specific value?

        interface IInterface
        {
            string GetMyString();
        }

Use like:

        var mock = mocks.Stub<IInterface>();
        mock.Stub(a => a.GetMyString()).Return("kees");
        mocks.ReplayAll();//don't forget or you will get null

Mocking methods with parameters and return values

        interface IInterface
        {
            string  GetMyString(string a);
        }

Always returning the same value

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

Returning based on input

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

Resulting in rock->paper and paper->scissor

  • No labels