Assert.Throws<> Over ExpectedException

Writing unit tests that expects a given type of exception under given circumstances is essential for any test suite. Although it is useful to use the correct assertion types when testing for exceptions. In this post I will provide some guidance on why to use Assert.Throws<>() instead of ExpectedException.

Using the ExpectedException:

  1. ///<summary>
  2. /// Testing exception handling
  3. ///</summary>
  4. [Test]
  5. [ExpectedException(typeof(ArgumentNullException))]
  6. publicvoid WhateverTestName()
  7. {
  8.     // Arrange
  9.     var sut = newSystemUnderTest();
  10.     // Act
  11.     // Assert
  12.     sut.MethodThatThrowsEception();
  13. }

 

In the above example whenever / wherever an exception of the given type is thrown inside the test, the test is considered passed.

A refactored example:

  1. ///<summary>
  2. /// Testing exception handling
  3. ///</summary>
  4. [Test]
  5. publicvoid WhateverTestName()
  6. {
  7.     // Arrange
  8.     var sut = newSystemUnderTest();
  9.     // Act
  10.     // Assert
  11.     Assert.Throws<ArgumentNullException>(() => sut.MethodThatThrowsEception());
  12. }

 

Now, instead of using the ExpectedException, I use Assert.Throws<>(). This provides a number of benefits / advantages:


comments powered by Disqus