Monday, January 28, 2013

Why All Those Lambdas in NUnit Tests?

I'm sure this is obvious, but I just figured it out. Suppose you are testing to verify that an expected System.Exception is thrown. Why does the first of these tests fail, but the second one passes?


[Test]
public void Test_Expected_Exception()
{
  Assert.That(someMethodThatThrowsAnException(), Throws.InstanceOf<System.Exception>());
}
[Test]
public void Test_Expected_Exception()
{
  Assert.That(() => someMethodThatThrowsAnException(), Throws.InstanceOf<System.Exception>());
}
The reason is that the first method call executes before NUnit can do anything with the assertion predicate (the fancy name for the second parameter), whereas the second creates a delegate that can be called by the testing framwork inside of a try/catch block. The catch block can then verify that the exception thrown matches the type specified. Basically, the "()=> someMethod()" creates something that can be called later, when the test framework is good and ready.

No comments:

Post a Comment