Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning value that was passed into a method

Tags:

c#

mocking

moq

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?

like image 488
Steve Dunn Avatar asked Jun 15 '09 15:06

Steve Dunn


People also ask

What is a value passed into a method called?

Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order.

What does it mean when a method returns a value?

In simple terms, it means to return the value to caller of the method... So, in your example, the method getX would return the value of x to the caller, allowing them access to it.

What happens when a return statement in a method is reached?

A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function.

What is a value passed into a method called in Java?

Pass-by-value means that when you call a method, a copy of each actual parameter (argument) is passed.


2 Answers

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

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

Or slightly more readable:

.Returns<string>(x => x); 
like image 198
mhamrah Avatar answered Sep 23 '22 10:09

mhamrah


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.

like image 20
Steve Avatar answered Sep 24 '22 10:09

Steve