Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 214 Vote(s) - 3.68 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Returning value that was passed into a method

#1
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?
Reply

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

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

Or slightly more readable:

.Returns<string>(x => x);
Reply

#3
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.
Reply

#4
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);
Reply

#5
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
});
```
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through