Export (0) Print
Expand All

ExpectedExceptionAttribute Class

Indicates that an exception is expected during test method execution. This class cannot be inherited.

Namespace:  Microsoft.VisualStudio.TestTools.UnitTesting
Assembly:  Microsoft.VisualStudio.QualityTools.UnitTestFramework (in Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll)

[AttributeUsageAttribute(AttributeTargets.Method, AllowMultiple = false)]
public sealed class ExpectedExceptionAttribute : Attribute

This attribute is used to test whether an expected exception is thrown. The test method will pass if the expected exception is thrown. The test will fail if the thrown exception inherits from the expected exception.

If a test has both an ExpectedException attribute and an Assert statement, either one can cause the test to fail. To determine whether the attribute or the statement caused the test to fail, double-click the test result to open the Results Details page for the test. For more information about test results, see Test Results Reported.

This attribute can be specified on a method. There can be only one instance of this attribute on a method.

For more information about how to use attributes, see Extending Metadata Using Attributes.

The following class contains the method to test:

using System;

namespace MyCSNamespace
{
    public class DivisionClass
    {
        public int Divide(int numerator, int denominator)
        {
            return numerator / denominator;
        }
    }
}

The following test method tests the Divide method of the DivisionClass object. It tests for the existence of a DivideByZeroException.

using Microsoft.VisualStudio.TestTools.UnitTesting;
using MyCSNamespace;

namespace MyCSTestProject
{
    [TestClass()]
    public class DivisionClassTest
    {
        [TestMethod()]
        [ExpectedException(typeof(System.DivideByZeroException))]
        public void DivideTest()
        {
            DivisionClass target = new DivisionClass();
            int numerator = 4;
            int denominator = 0;
            int actual;
            actual = target.Divide(numerator, denominator);
        }
    }
}

System.Object
  System.Attribute
    Microsoft.VisualStudio.TestTools.UnitTesting.ExpectedExceptionAttribute

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Community Additions

ADD
Show:
© 2014 Microsoft