unit test with lambda fail using rhino mock

前端 未结 2 538
后悔当初
后悔当初 2021-01-26 09:02

If I have this test

Expect.Call(_session.Single(x => x.Email == userModel.Email)).Repeat.Once().Return(null);

Telling me

相关标签:
2条回答
  • 2021-01-26 09:19

    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

    0 讨论(0)
  • 2021-01-26 09:39

    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.

    0 讨论(0)
提交回复
热议问题