George Mauer
George Mauer

Reputation: 122062

Rhino Mocks: How to return conditional result from a mock object method

I would like to do something like the following but can't seem to get the syntax for the Do method quite right.

var sqr = new _mocks.CreateRenderer<ShapeRenderer>();
Expect.Call(sqr.CanRender(null)).IgnoreArguments().Do(x =>x.GetType() == typeof(Square)).Repeat.Any();

So basically, I would like to set up the sqr.CanRender() method to return true if the input is of type Square and false otherwise.

Upvotes: 2

Views: 1441

Answers (3)

Timothy Walters
Timothy Walters

Reputation: 16874

As of Rhino Mocks 3.5 you can now do the following:

Expect.Call( sqr.CanRender( Arg<Shape>.Is.TypeOf<Square>() ).Repeat.Any();

Look at this wiki article for more information.

Upvotes: 1

Iain
Iain

Reputation: 10749

If you aren't able to use .Net Framework 3.5 (required by Cristian's answer) and therefore don't have access to the System.Func delegates then you'll need to define your own delegate.

Add to the class member:

private delegate bool CanRenderDelegate(Shape shape)

The expectation becomes:

Expect.Call(sqr.CanRender(null))
    .IgnoreArguments()
    .Do((CanRenderDelegate) delegate(Agent x){return x.GetType() == typeof(Square);})
    .Repeat.Any();

Upvotes: 2

Cristian Libardo
Cristian Libardo

Reputation: 9258

Are you looking for this?

Expect.Call(sqr.CanRender(null)).IgnoreArguments()
    .Do((Func<Shape, bool>) delegate(Agent x){return x.GetType() == typeof(Square);})
    .Repeat.Any();

EDIT: The answer was correct in spirit bu the original syntax did not quite work.

Upvotes: 3

Related Questions