简体   繁体   English

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

[英]Rhino Mocks - Mocking collection with ref/out arguments

I'm still learning Rhino mocks and have a question about it. 我还在学习犀牛嘲笑并对此有疑问。 For example - I have a function in mocked interface: 例如 - 我在mocked界面中有一个函数:


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



As you see the function 'FunctionGetCollection' will receive 2 parameters passed as 'ref' and return another class as 'function-answer'. 如您所见,函数'FunctionGetCollection'将接收作为'ref'传递的2个参数,并将另一个类作为'function-answer'返回。 Can you help me to stub this funciton ? 你能帮我把这个功能存根吗? I need to be able to use: 我需要能够使用:

  • function will return different collection (based in place in code not on parameters) 函数将返回不同的集合(基于代码而不是参数)
  • function will return different AnswerObject 函数将返回不同的AnswerObject

The syntax is not very nice. 语法不是很好。 It is not used very often and uses the old-style Rhino.Mocks.Constraints . 它不经常使用并使用旧式的Rhino.Mocks.Constraints

This piece of code sets up a mock that replaces all the ref-arguments with new values. 这段代码设置了一个模拟,用新值替换所有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);

If you want to keep the values as they are passed to the mock, you need to implement this in a WhenCalled block: 如果要在传递给模拟时保留值,则需要在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);

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

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