Dashboard > MbUnit > ... > MbUnit Home > ExpectedExceptionAttribute
  MbUnit Log In View a printable version of the current page.  
  ExpectedExceptionAttribute
Added by Jonathan de Halleux, last edited by Graham Hay on May 15, 2007  (view change)
Labels: 
(None)

The ExpectedExceptionAttribute is a [TestDecorator] that enables you to create negative tests, i.e. tests that check that your application fails the way it should.

Use this [CustomAttribute] to tag a test with the expected exception type:

[Test]
[ExpectedException(typeof(MyCustomException))]
public void NegativeTest()
{ ... }

A classical example of usage is to check that a method checks that it's arguments are non-null.

public class Foo
{
   public Object Method(Object o)
   {
       return o.ToString();
    }
}

[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void MethodArgumentNull()
{
   Foo foo = new Foo();
   foo.Method(null);
}

This test will fail because the thrown exception (NullReferenceException) is not of the right type (ArgumentNullException).

As of version 2.4, you can also test the expected message:

[Test, ExpectedException(typeof(NotImplementedException), "This should match.")]
public void ExceptionAndExpectedMessage()
{
    throw new NotImplementedException("This should match.");
}

and the inner exception:

[Test, ExpectedException(typeof(NotImplementedException), typeof(ArgumentException))]
public void ExceptionAndInnerException()
{
    throw new NotImplementedException("", new ArgumentException());
}

Site powered by a free Open Source Project / Non-profit License (more) of Confluence - the Enterprise wiki.
Learn more or evaluate Confluence for your organisation.
Powered by Atlassian Confluence, the Enterprise Wiki. (Version: 2.2.9 Build:#527 Sep 07, 2006) - Bug/feature request - Contact Administrators