Assert.IsTrue(ThrowsException(() => object.Method()));

While reading this post, I came across an interesting line of code:

    1: Assert.IsTrue(ThrowsException<UpdateException>(() => rb.Update(b2)));
    2:  
    3: ThrowsException<E> is:
    4:  
    5:      private static bool ThrowsException<E>(Action f) where E : Exception
    6:      {
    7:             try
    8:             {
    9:                 f();
   10:             }
   11:             catch (E)
   12:             {
   13:                 return true;
   14:             }
   15:             catch
   16:             {
   17:             }
   18:  
   19:             return false;
   20:      }

Clever!

Comments