4

Unit Testing Expression Tree Equality

Posted in .Net, C#, Unit Testing at August 25th, 2009 by Ben / 4 Comments »

Sometimes you need to test whether two expressions are the same. However when you do a simple AreEqual() test on two expressions that look the same you get a negative result.

This method will fail

[TestMethod]
public void TestDoesNotWork()
{
  Expression<Func<int, int>> expressionA = x => x + 1;
  Expression<Func<int, int>> expressionB = x => x + 1;

  Assert.AreEqual(expressionA, expressionB);
}

This looks like it should work however it doesn’t. This is because when using anonymous expressions/delegates the CLR does some magic behind the scene to add a method on the fly, creating a new instance for every anonymous expression/delegate.

So if you have two expressions that are syntactically the same but not the same reference the easiest way to ensure they are the same is to compile the expression and invoke it comparing the resultant value.

[TestMethod]
public void TestDoesWork()
{
  Expression<Func<int, int>> expressionA = x => x + 1;
  Expression<Func<int, int>> expressionB = x => x + 1;

  Assert.AreEqual(expressionA.Compile().Invoke(3), expressionB.Compile().Invoke(3));
}

An alternate approach would be to de-construct each constituent part of the expression trees comparing each part as you go. This however is far more complex.

For a more real world example that involves using Rhino mocks and Expect calls please read on:

Read the rest of this entry »