Export (0) Print
Expand All

ExpectedExceptionBaseAttribute Class

This is a base class for attributes that specify to expect an exception from a unit test.

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

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

[AttributeUsageAttribute(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public abstract class ExpectedExceptionBaseAttribute : Attribute

The ExpectedExceptionBaseAttribute type exposes the following members.

  NameDescription
Protected methodExpectedExceptionBaseAttribute()Initializes a new instance of the ExpectedExceptionBaseAttribute class.
Protected methodExpectedExceptionBaseAttribute(String)Initializes a new instance of the ExpectedExceptionBaseAttribute class.
Top

  NameDescription
Protected propertyNoExceptionMessageInfrastructure.
Protected propertyTestContextInfrastructure.
Public propertyTypeIdWhen implemented in a derived class, gets a unique identifier for this Attribute. (Inherited from Attribute.)
Top

  NameDescription
Public methodEqualsInfrastructure. Returns a value that indicates whether this instance is equal to a specified object. (Inherited from Attribute.)
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodGetHashCodeReturns the hash code for this instance. (Inherited from Attribute.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodIsDefaultAttributeWhen overridden in a derived class, indicates whether the value of this instance is the default value for the derived class. (Inherited from Attribute.)
Public methodMatchWhen overridden in a derived class, returns a value that indicates whether this instance equals a specified object. (Inherited from Attribute.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Protected methodRethrowIfAssertExceptionThrows the exception again if it is an AssertFailedException or an AssertInconclusiveException.
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Protected methodVerifyInfrastructure.
Top

  NameDescription
Explicit interface implemetationPrivate method_Attribute.GetIDsOfNamesMaps a set of names to a corresponding set of dispatch identifiers. (Inherited from Attribute.)
Explicit interface implemetationPrivate method_Attribute.GetTypeInfoRetrieves the type information for an object, which can be used to get the type information for an interface. (Inherited from Attribute.)
Explicit interface implemetationPrivate method_Attribute.GetTypeInfoCountRetrieves the number of type information interfaces that an object provides (either 0 or 1). (Inherited from Attribute.)
Explicit interface implemetationPrivate method_Attribute.InvokeProvides access to properties and methods exposed by an object. (Inherited from Attribute.)
Top

By implementing your own expected exception verification. you can specify additional information and requirements that the built-in methods of the ExpectedExceptionAttribute class cannot handle, such as the following:

  • Verifying the state of the exception.

  • Expecting more than one type of exception.

  • Displaying a custom message when a wrong type of exception is thrown.

  • Controlling the outcome of a negative test.

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

The following class contains the method to test.

using System;

namespace CSExample
{
    public class DivisionClass
    {
        private int fraction;

        public int Divide(int numerator, int denominator)
        {
            return numerator / denominator;
        }
    }
}

The following custom attribute class, ExpectedArithmeticException, derives from the ExpectedExceptionBaseAttribute class to verify an exception type and message. The ExpectedArithmeticException attribute verifies that a test method throws an exception of a type that is or derives from System.ArithmeticException. It also verifies that the exception message matches the specified exception message. The unit test will pass because it throws a DivideByZeroException, which derives from ArithmeticException, and the specified exception message matches the message of the exception that is thrown by the unit test.

using CSExample;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TestProject1
{
    public sealed class ExpectedArithmeticException : ExpectedExceptionBaseAttribute
    {
        private string exceptionMessage;
        private string wrongExceptionMessage;

        public string WrongExceptionMessage
        {
            get
            {
                return wrongExceptionMessage;
            }
            set
            {
                wrongExceptionMessage = value;
            }
        }

        public ExpectedArithmeticException(string expectedExceptionMessage) : this(expectedExceptionMessage, "No exception was thrown.")
        {
        }

        public ExpectedArithmeticException(string expectedExceptionMessage, string noExceptionMessage)
            : base(noExceptionMessage)
        {
            exceptionMessage = expectedExceptionMessage;
            WrongExceptionMessage = "The exception that was thrown does not derive from System.ArithmeticException.";
        }

        protected override void Verify(System.Exception exception)
        {
            Assert.IsNotNull(exception);

            // Handle assertion exceptions from assertion failures in the test method, since we are not interested in verifying those
            base.RethrowIfAssertException(exception);

            Assert.IsInstanceOfType(exception, typeof(System.ArithmeticException), wrongExceptionMessage);
            Assert.AreEqual(exceptionMessage, exception.Message, "Could not verify the exception message.");
        }
    }


    [TestClass()]
    public class DivisionClassTest
    {

        /* This test will pass because it thows a System.DivideByZeroException which derives from System.ArithmeticException. */
        [TestMethod()]
        [ExpectedArithmeticException("Attempted to divide by zero.", "An exception was expected, but no exception was thrown.", WrongExceptionMessage = "The wrong type of exception was thrown.")]
        public void DivideTest()
        {
            DivisionClass target = new DivisionClass();
            int numerator = 5;
            int denominator = 0;
            int actual;
            actual = target.Divide(numerator, denominator);
        }

    }
}

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