Returning value that was passed into a method

后端 未结 3 902
闹比i
闹比i 2020-12-07 08:36

I have a method on an interface:

string DoSomething(string whatever);

I want to mock this with MOQ, so that it returns whatever was passed

相关标签:
3条回答
  • 2020-12-07 08:53

    Even more useful, if you have multiple parameters you can access any/all of them with:

    _mock.Setup(x => x.DoSomething(It.IsAny<string>(),It.IsAny<string>(),It.IsAny<string>())
         .Returns((string a, string b, string c) => string.Concat(a,b,c));
    

    You always need to reference all the arguments, to match the method's signature, even if you're only going to use one of them.

    0 讨论(0)
  • 2020-12-07 09:04

    The generic Returns<T> method can handle this situation nicely.

    _mock.Setup(x => x.DoSomething(It.IsAny<string>())).Returns<string>(x => x);
    

    Or if the method requires multiple inputs, specify them like so:

    _mock.Setup(x => x.DoSomething(It.IsAny<string>(), It.IsAny<int>())).Returns((string x, int y) => x);
    
    0 讨论(0)
  • 2020-12-07 09:13

    You can use a lambda with an input parameter, like so:

    .Returns((string myval) => { return myval; });
    

    Or slightly more readable:

    .Returns<string>(x => x);
    
    0 讨论(0)
提交回复
热议问题