unit test with lambda fail using rhino mock

冷暖自知 提交于 2019-12-02 13:38:14

The lambda in your unit test compiles into a class-level method (a method inside your unit test). Inside your controller, a different lambda compiles into a class-level method (inside the controller). Two different methods are used so Rhino Mocks shows the expectation error. More here: http://groups.google.com/group/rhinomocks/browse_frm/thread/a33b165c16fc48ee?tvc=1

Unfortunately lambdas in C# use reference equality, not value equality. Try the following:

Func<bool> f1 = () => true;
Func<bool> f2 = () => true;
Console.WriteLine("f1 == f2 results in " + (f1 == f2));

Guess what? The answer is False.

It's also false for Expression...

Expression<Func<bool>> f1 = () => true;
Expression<Func<bool>> f2 = () => true;
Console.WriteLine(f1.ToString());          // Outputs "() => True"
Console.WriteLine("a1 == a2 results in " + (f1 == f2)); // False

Unfortunately the best way to solve this (and its ugly) in C# (and therefore Rhino Mocks) is to use ToString() on Expressions and compare those.

Expression<Func<bool>> f1 = () => true;
Expression<Func<bool>> f2 = () => true;
Console.WriteLine(f1.ToString());        // Outputs "() => True"
Console.WriteLine("a1 == a2 results in " + (f1.ToString() == f2.ToString()));  // True

You have to be careful with this technique as two Expressions, "x => x" and "y => y", although equivalent functionally, will still evaluate to false due to the different parameters. Also be aware that you must do this with Expression and not Func or Action for this ToString() trick to work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!