I am using Moq to mock some interface. Here it is:
var titleGenerator = new Mock<ITitleGenerator>();
titleGenerator.Setup(t => t.GenerateTitle()).Returns(Guid.NewGuid().ToString);
Console.WriteLine(titleGenerator.Object.GenerateTitle());
Console.WriteLine(titleGenerator.Object.GenerateTitle());
It prints the same value twice. But if I replace the second line with this:
titleGenerator.Setup(t => t.GenerateTitle()).Returns(() => Guid.NewGuid().ToString());
it returns unique values on each call.
I always thought method groups are just a shortcut to lambda expression. Is there any difference? I tried searching the documentations for any explanation. Can someone enlighten me?
It looks like the method group evaluates the expression once and somehow caches it? Or does it have something to do with Moq?
In your first example, you're passing the ToString function of a single Guid, which then gets called on every invocation. It's equivalent to this:
Guid guid = Guid.NewGuid();
titleGenerator.Setup(t => t.GenerateTitle()).Returns(guid.ToString)
In your second example, you're passing a function that first creates a new Guid and then invokes ToString() on it.
The difference is in the inputs. In the first case the "method group" is actually a delegate for Guid.ToString. But since it requires an instance as "input", the instance is part of the delegate expression, and so the same "input" is used each time.
It would be equivalent to:
var titleGenerator = new Mock<ITitleGenerator>();
Guid g = Guid.NewGuid();
titleGenerator.Setup(t => t.GenerateTitle()).Returns(g.ToString);
In the second case, the delegate has no input. The Guid instance is calculated within the delegate, so a new Guid is used each time.
For an equivalent example that might be easier to understand, the code:
var id = 1;
Func<string> f = id.ToString;
id = 2;
Console.WriteLine(f()); // 1
will write "1", whereas:
var id = 1;
Func<string> f = () => id.ToString();
id = 2;
Console.WriteLine(f()); // 2
will write "2".
In the first case, the delegate (Func<> instance) f is created with the value 1 as Target and the method info for string int.ToString() as Method. The later reassignment to id does not affect f.
In the second case, things will be more indirect. The compiler will generate a new method that corresponds to the => arrow. The local variable id is captured or closed over (is in the closure of the lambda). That means, behind the scenes, id is really promoted to a field somewhere (compiler's choice). When your method mentions id, it really accesses that field. And the compiler-generated method corresponding to the => arrow also reads that field. Now the Func<> is created with its Method property being this compiler-generated method. Because of all this, the result will be "2" here. That is the closure semantics of anonymous functions in C#.
Your original Moq example is just the same. The Returns overload in question takes an argument Func<TResult> valueFunction where TResult is string in your use. That valueFunction is what I called f in my simpler example.
Related
Trying to set up a function to moq a call to a db to return an object
The function I am trying to mock is
res = ReservationMongo.GetById<res.Reservation>(request.ReferenceNumber);
Which is defined as
T GetById<T>(object id, bool fixId = false);
However in my set up I am encountering this error:
an expression tree may not contain a call or invocation that uses optional arguments
My setup:
Mock <IMongoDBService> resMock = new Mock<IMongoDBService>();
resMock.Setup(x => x.GetById<Reservation>(request.ReferenceNumber)).Returns(res1);
Optional parameters will also need to be included in the setup of the function to mock, even if they are not being explicitly used in the invocation of the member.
//...
Reservation res1 = new Reservation {
name = "bob",
age = "29",
occupant.name = "bob G",
occupant.name = string.empty
};
Mock<IMongoDBService> resMock = new Mock<IMongoDBService>();
resMock
.Setup(x => x.GetById<Reservation>(It.IsAny<int>(), It.IsAny<bool>())
.Returns(res1);
//...
Note the use of It.* argument matcher to allow for any argument values to be entered and still get the desired behavior
Reference Moq Quickstart
This is not explicitly a Moq issue, this is a expression tree issue. Expression trees do not allow optional arguments because that is something that is resolved at compile time as in CLR does not support the concept of optional arguments. So to fix your problem you will need to be explicit and put the value in, which if you are were counting on the default argument you are in luck just use that.
I have to convert the following expression from VB.NET to C#:
Dim query = (From egyosztaly As UpdateItemBase In UpdateItemCollectionRemote
Group Join egystudent As UpdateItemBase In UpdateItemCollectionLocal On egyosztaly.HashCode Equals egystudent.HashCode
Into csoport = Group
From egycsoportelem In csoport.DefaultIfEmpty
Select New ComparedUpdateItem With {.Remote = egyosztaly, .Local = egycsoportelem}).ToList()
My attempt:
var query = (from egyosztaly in UpdateItemCollectionRemote
join egystudent in UpdateItemCollectionLocal on egyosztaly.HashCode equals egystudent.HashCode into csoport
from egycsoportelem in csoport.DefaultIfEmpty
select new ComparedUpdateItem() { Remote = egyosztaly, Local = egycsoportelem }).ToList();
The second "from" part is not understandable by C#.
Thanks for help!
In C# you need to be explicit when you call a method with no arguments, to provide empty parentheses. Identifiers without parens are usually considered properties, not methods (functions in vb nomenclature)
var query = (
from egyosztaly in UpdateItemCollectionRemote
join egystudent in UpdateItemCollectionLocal on egyosztaly.HashCode equals egystudent.HashCode into csoport
from egycsoportelem in csoport.DefaultIfEmpty()
select new ComparedUpdateItem() {
Remote = egyosztaly,
Local = egycsoportelem
}
).ToList();
DefaultIfEmpty is a method and you want to call it, so you need to add ()
In VB developers often don't really care about the same set of things we care about in C#; in C# we care quite a lot about things like naming and case sens:
class SomeName{ //class names PascalCase
private int _someInt; //private vars camelCase, usually underscore led
public int SomeInt { get { return _someInt; } } //public properties PascalCase
public void SomeMethod(int someArgument){ //methods PascalCase, arguments camelCase
void localFunction() { ... }; //local function, usually camelCase
int localVariable = 0; //local vars camelCase
SomeStaticClass.SomeMethodWithNoArgs(); //Static classes PascalCase, method calls with no args must include ()
someInstance.SomeMethod(1);
var x = new Thing { X = 1 }; //new calling default constructor no longer requires () if initializing properties
Thing x = new(); //but does if new stands alone
}
}
Ultimately, it's usually possible to look at some code and know what is going on just from the casing; the only time it gets hazy is in scenarios like this:
AddAction(Foo.SomeThing) //AddAction is a method that takes.. er..
Foo.SomeThing here could be a property of an instance called Foo or it could be a method of a type called Foo - when we're calling a method that takes a method (a delegate) as a parameter we pass the method name without the () - putting () would call the method and pass the result
AddAction(Foo.SomeThing) //SomeThing could be a property or a method
AddAction(Foo.SomeThing()) //SomeThing is a method, called and its return value passed to AddAction
In latest VS properties and methods are colored differently which helps with this case. For a use case where you have "a method that takes a method", you'll come across that quite a lot in LINQ, but I'll give an example using List:
var strings = new List<string>() {"hello","world"};
strings.ForEach(Console.WriteLine);
ForEach is a method that takes a method argument. List will loop over itself calling the supplied method once for every item. The method that is passed must accept a string as an argument, like Console.WriteLine does. All the strings in the list will print to the console. It's legal to pass the method name without the () because we don't want to call the WriteLine method and pass the result to ForEach (actually WriteLine has no result); we want to pass the WriteLine method itself to ForEach
Similarly this syntax "creates a mini method":
x => something_here;
So this is legal too:
strings.ForEach(x => Console.WriteLine(x.ToUpper()));
The whole x => Console.WriteLine(x.ToUpper()) thing is "a method that takes a parameter called x, of type that will be deduced from ForEach's signature which for a list of strings is 'a method that takes a single string argument'". In VB the equivalent is:
strings.ForEach(Function(x) Console.WriteLine(x.ToUpper));
(And of course VB wouldnt care if if was ToUpper or ToUpper() but C# people care quite a bit about these detils because it's vital to help understand a program and get clues as to what is what) :)
I have this code:
int pictureId=10;
string cacheKey = string.Format(ModelCacheEventConsumer.PICTURE_URL_MODEL_KEY, pictureId);
return _cacheManager.Get(cacheKey, () =>
{
var url = _pictureService.GetPictureUrl(pictureId, showDefaultPicture: false);
//little hack here. nulls aren't cacheable so set it to ""
if (url == null)
url = "";
return url;
});
What exactly this part of code means:"
() =>
{"
var url =...."
Does it mean that function, which returns URL, is executed for every row from cache? What is then return type - list?
URL of documentation of this syntax?
Second parameter to _cacheManager.Get() method is an anonymous method that captures pictureId and among other things.
https://msdn.microsoft.com/en-us/library/bb397687.aspx
C# Lambda expressions: Why should I use them?
To figure out the returned type, try using var keyword and creating a local variable: instead of return _cacheManager.Get() write var x = _cacheManager.Get() followed by return x. Then simply hover over the keyword var in Visual Studio.
What exactly this part of code means
It's just passing a method by parameter.
Does it mean that function, which returns URL, is executed for every row from cache?
Only the content of the method Get of the object _cacheManager can answer this.
What is then return type - list?
The return type is a string, since your variable url is a string.
What exactly this part of code means:
Well, lambda expression is a "shortcut" for delegate, and delegate is a reference to a callback function (in a very simple explanation). So this is a function which will be called inside your Get method of cache manager, which expects to have a Func delegate as a second param
Does it mean that function, which returns URL, is executed for every row from cache?
I think it will executes for row which has a key value the same as the value of cacheKey variable.. So, only one time (if keys are unique)
What is then return type - list?
The return type is string, because if result of GetPictureUrl is null it returns empty string. And calling this method is expecting to have a string in a result also
I have a bit of confusion with this C# syntax.
I'm trying to assign an arbitrary delegate to a class.
I have a delegates defined as
delegate string stringCB(string s);
delegate int intCB(int i);
I have a class
class run_by_name {
public string name {get;set;}
public Delegate method {get;set;}
};
And I'm trying to instantiate it
run_by_name myfuc = new run_by_name(){
name = "my name",
method = new stringCB(string s) {
return " testing " + s;
};
};
I'm really not clear how to assign to a delegate when there's a return type. Also I'm not sure how to call that method later on syntactically.
Why I'm doing this? Well I'm just writing some code that follows a pattern I use in JS a lot for event handling, I'm just making an "object" I can assign arbitrary functions to for a generic event handler that's created rather than defined. (important)
Also, alternatives to using delegates are welcome. :)
EDIT: How I might use it later
I don't have that written yet but Im pretty sure I'll be doing this.
List<run_by_name> callbacks = new List<run_by_name>();
/* lets say this is initialized and filled at this point */
public object FindAndRunCallback(string Name, object input) {
foreach(var cb in callbacks) {
if( cb.name == Name )
return cb.method(input);
}
return null;
}
Here's the syntax you need to get your current code working:
method = new stringCB((string s) => {
return " testing " + s;
})
Or, using lambda expressions:
method = new stringCB(s =>" testing " + s)
You could later invoke the method like so:
string result = (string) myfuc.method.DynamicInvoke("hello");
Without knowing more about your use case, it's hard to recommend other approaches, but I'd recommend at least looking into the following:
Events: Your description sounds very close to the common pattern for events and event handlers in C#. Your event defines the delegate type that is used to handle it, and code elsewhere can subscribe to that event with methods that match that delegate type. By convention, people usually pass a sender object as the first parameter, and some strongly-typed EventArgs so that subscribers don't have to guess at what data is going to be available when the event fires.
Func<> and Action<> variants: As C# has evolved into a more functional language, programmers have trended away from using custom delegate types, and toward using the provided variants of Func<> and Action<>. Since the arguments are strongly-typed still, you get most of the advantages of a compiled language, but use a little "duck typing" for the actual function you pass around.
For example, you could give your class a generic type based on what types you expect your delegate to deal with:
class run_by_name<T> {
public string name {get;set;}
public Func<T, T> method {get;set;}
};
Then use it:
var myfuc = new run_by_name<string>{
name = "my name",
method = s =>" testing " + s
};
string result = myfuc.method("hello");
dynamic: This keyword allows you to late-bind actions on any object. You lose the advantages of a compiled language, but it improves interoperability with more dynamic languages immensely. For example, an object can be created via JSON, and you can access the properties on it without declaring a special type for that object, just like you can in Javascript.
For example, if you changed your method declaration to this:
public dynamic method {get;set;}
Then you could simply say:
string result = myfuc.method("hello");
You have seceral choices. the strinCB constructor expects a method, that takes a string parameter and returns a string. If you have an existing method, you can pass it's name to the constructor, or you can create an anonymous method wither by delegate syntax like this:
method = new stringCB(delegate(string s)
{
return " testing " + s;
})
Or using a lambda expression:
method = new stringCB(s =>
{
return " testing " + s;
})
Then you can call it like this: myfuc.method.DynamicInvoke(YourParameter);
Normally, calling a delegate's method is pretty easy like this:
Func<int, int, int> sum = (x, y) => x + y;
Console.WriteLine(sum(2,3)); // with the name of delegate
Console.WriteLine(sum.Invoke(2,3)); // or using Invoke method
But in this case, you need to use DynamicInvoke because the type of your property is Delegate.
Apart from that .NET Framework has some useful built-in delegate types, such as Func,Action and Predicate etc. You can use them instead of creating your own delegate as long as they satisfy your needs. For example in this case you can use a Func<string,string> instead of stringCB.
I was going through Jeffrey Palermo's book and came across this syntax.
private void InitializeRepositories()
{
Func<IVisitorRepository> builder = () => new VisitorRepository();
VisitorRepositoryFactory.RepositoryBuilder = builder;
}
What does it mean?
() => indicates a lambda expression that takes no arguments.
In general, it means a function with no arguments.
In this particular example, it creates an anonymous function with no arguments that returns a new VisitorRepository(); object every time.
Func<IVisitorRepository> stands for a delegate which takes no arguments and returns a IVisitorRepository. The creation of that delegate is a lambda function:
() //means no parameters
=> new VisitorRepository()// means it returns a new VisitorRepository
() is the place where you place your variables
Example a common event handled would look like (sender, args)
=> // means throw these parameter into this method
after => you can either drop a one line execution thing like new VisitorRepositor()
OR
you can place a whole function like
Func<IRepository> = (sender, args) =>
{
var myObject = (SomeObject)sender;
return new VisitorReposiroty { id = myObject.SomeId };
}
As other stated it's lambda expression and it really clears your code from method or function that handle a specific event.
Once you read them good it's really damn useful.
The () => syntax is a lambda expression. Lambdas were introduced in C# 3.0 and are used to define an anonymous method for a delegate.
The delegate is defined using the generic Func. So in this case the signature for the delegate is: no input parameters and one output parameter of type IVisitorRepository.
So on the left side of the => lambda array are the names of the input parameters. In case of no input parameters just write (). On the rightside of the => lambda is the code to return the output parameter, in this example: new VisitorRepository().
I suggest read more about lambda expressions in C# to fully understand this code. There is also a generic delegate involved, so you need understanding of Generics and Delegates as well.
Func is a delegate without parmeter and with an IVisitorRepository return value.
() => is a lambda expression creating an anonymous method.
new VisitorRepository() is the content of this anonymous method.
so this line is creating a delegate which is pointing to a anonymous method, which is returning an instance of VisitorRepository.
Func<IVisitorRepository> builder = () => new VisitorRepository()
In the next line, you set the value of a static property to this just created delegate.
VisitorRepositoryFactory.RepositoryBuilder = builder;
After this you can use the property to call the anonymous method, which is creating a new instance of VisitorRepository.
IVisitorRepository repository = VisitorRepositoryFactory.RepositoryBuilder();
In this case, repository will be an instance of VisitorRepository.
It means a function takes no parameters, like:
delegate() {//}