Rhino Mocks - 使用ref / out参数模拟集合

时间:2012-01-24 09:01:21

标签: c# rhino-mocks

我还在学习犀牛嘲笑并对此有疑问。例如 - 我在模拟界面中有一个函数:


    public interface ISomeObject
    {
      string Name {get; set;}
      int Id {get;set;}
    }

    // This class will be returned as and answer to function call
    public class AnswerObject
    {
        public bool IfError {get;set;}
    }

    // Main interface
    public interface IClass
    {
        AnswerObject FunctionGetCollection(ref ICollection <ISomeObject> ListOfInternalObjects, ref int Number);
    }



   如您所见,函数'FunctionGetCollection'将接收作为'ref'传递的2个参数,并将另一个类作为'function-answer'返回。你能帮我把这个功能存根吗?我需要能够使用:

  • 函数将返回不同的集合(基于代码而不是参数)
  • 函数将返回不同的AnswerObject

1 个答案:

答案 0 :(得分:5)

语法不是很好。它不经常使用并使用旧式Rhino.Mocks.Constraints

这段代码设置了一个模拟,用新值替换所有ref-arguments。

AnswerObject answerObject;
ICollection <ISomeObject> collection;
int number;

IClass iClassMock = MockRepository.GenerateMock<IClass>();
iClassMock
  .Stub(x => x.FunctionGetCollection(
    ref Arg<ICollection <ISomeObject>>.Ref(Is.Anything(), collection).Dummy,
    ref Arg<int>.Ref(Is.Anything(), number).Dummy);
  .Return(answerObject);

如果要在将值传递给模拟时保留这些值,则需要在WhenCalled块中实现它:

iClassMock
  .Stub(x => x.FunctionGetCollection(
    ref Arg<ICollection <ISomeObject>>.Ref(Is.Anything(), null).Dummy,
    ref Arg<int>.Ref(Is.Anything(), 0).Dummy);
  .WhennCalled(call =>
  {
    // reset the ref arguments to what had been passed to the mock
    // not sure if it also works with the int
    call.Arguments[0] = call.Arguments[0];
    call.Arguments[1] = call.Arguments[1];
  })
  .Return(answerObject);