简体   繁体   English

Rhino Mocks:如何从模拟对象方法返回条件结果

[英]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. 我想做类似以下的事情,但似乎无法正确理解Do方法的语法。

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. 因此,基本上,我想将sqr.CanRender()方法设置为在输入为Square类型时返回true,否则返回false。

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. 编辑:答案在精神上是正确的,但原始语法不太奏效。

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. 如果您无法使用.Net Framework 3.5( Cristian的答案要求 ),因此无法访问System.Func委托,则需要定义自己的委托。

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();

As of Rhino Mocks 3.5 you can now do the following: 从Rhino Mocks 3.5开始,您现在可以执行以下操作:

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

Look at this wiki article for more information. 有关更多信息, 请参见此Wiki文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM