![]() |
Returning value that was passed into a method - Printable Version +- 0Day Forums (https://0day.red) +-- Forum: Coding (https://0day.red/Forum-Coding) +--- Forum: C# (https://0day.red/Forum-C) +--- Thread: Returning value that was passed into a method (/Thread-Returning-value-that-was-passed-into-a-method) |
Returning value that was passed into a method - invitant11933 - 07-24-2023 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 in - something like: _mock.Setup( theObject => theObject.DoSomething( It.IsAny<string>( ) ) ) .Returns( [the parameter that was passed] ) ; Any ideas? RE: Returning value that was passed into a method - coloradoite703764 - 07-24-2023 You can use a lambda with an input parameter, like so: .Returns((string myval) => { return myval; }); Or slightly more readable: .Returns<string>(x => x); RE: Returning value that was passed into a method - chondrocostal556876 - 07-24-2023 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. RE: Returning value that was passed into a method - Sirbuckjumper3 - 07-24-2023 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); RE: Returning value that was passed into a method - Drfoliage1 - 07-24-2023 For those who are not using Moq, there's a way with NSubstitute. ``` mock.Method(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>()).Returns(callInfo => { var arg1 = callInfo[0].ToString(); var arg2 = callInfo[1].ToString(); var argN = callInfo[n-1].ToString(); return arg1 + arg2 + argN; //or whatever }); ``` |