unit test with lambda fail using rhino mock

前端 未结 2 539
后悔当初
后悔当初 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:39

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

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

    Guess what? The answer is False.

    It's also false for Expression...

    Expression> f1 = () => true;
    Expression> 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> f1 = () => true;
    Expression> 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.

提交回复
热议问题