다음을 통해 공유


ExpectedExceptionBaseAttribute 클래스

단위 테스트의 예외가 필요하도록 지정하는 특성의 기본 클래스입니다.

상속 계층 구조

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

네임스페이스:  Microsoft.VisualStudio.TestTools.UnitTesting
어셈블리:  Microsoft.VisualStudio.QualityTools.UnitTestFramework(Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll)

구문

‘선언
<AttributeUsageAttribute(AttributeTargets.Method, AllowMultiple := False, Inherited := True)> _
Public MustInherit Class ExpectedExceptionBaseAttribute _
    Inherits Attribute
[AttributeUsageAttribute(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public abstract class ExpectedExceptionBaseAttribute : Attribute
[AttributeUsageAttribute(AttributeTargets::Method, AllowMultiple = false, Inherited = true)]
public ref class ExpectedExceptionBaseAttribute abstract : public Attribute
[<AbstractClass>]
[<AttributeUsageAttribute(AttributeTargets.Method, AllowMultiple = false, Inherited = true)>]
type ExpectedExceptionBaseAttribute =  
    class
        inherit Attribute
    end
public abstract class ExpectedExceptionBaseAttribute extends Attribute

ExpectedExceptionBaseAttribute 형식에서는 다음과 같은 멤버를 노출합니다.

생성자

  이름 설명
Protected 메서드 ExpectedExceptionBaseAttribute() ExpectedExceptionBaseAttribute 클래스의 새 인스턴스를 초기화합니다.
Protected 메서드 ExpectedExceptionBaseAttribute(String) ExpectedExceptionBaseAttribute 클래스의 새 인스턴스를 초기화합니다.

위쪽

속성

  이름 설명
Protected 속성 NoExceptionMessage 인프라입니다.
Protected 속성 TestContext 인프라입니다.
Public 속성 TypeId 파생 클래스에서 구현된 경우 이 Attribute에 대한 고유 식별자를 가져옵니다. (Attribute에서 상속됨)

위쪽

메서드

  이름 설명
Public 메서드 Equals 인프라입니다. 이 인스턴스가 지정된 개체와 같은지 여부를 나타내는 값을 반환합니다. (Attribute에서 상속됨)
Protected 메서드 Finalize 가비지 수집에서 회수하기 전에 개체에서 리소스를 해제하고 다른 정리 작업을 수행할 수 있게 합니다. (Object에서 상속됨)
Public 메서드 GetHashCode 이 인스턴스에 대한 해시 코드를 반환합니다. (Attribute에서 상속됨)
Public 메서드 GetType 현재 인스턴스의 Type을 가져옵니다. (Object에서 상속됨)
Public 메서드 IsDefaultAttribute 파생 클래스에서 재정의된 경우 이 인스턴스의 값이 파생 클래스의 기본값인지 여부를 나타냅니다. (Attribute에서 상속됨)
Public 메서드 Match 파생 클래스에서 재정의된 경우 이 인스턴스가 지정된 개체와 같은지 여부를 나타내는 값을 반환합니다. (Attribute에서 상속됨)
Protected 메서드 MemberwiseClone 현재 Object의 단순 복사본을 만듭니다. (Object에서 상속됨)
Protected 메서드 RethrowIfAssertException AssertFailedException 또는 AssertInconclusiveException인 경우 예외를 다시 throw합니다.
Public 메서드 ToString 현재 개체를 나타내는 문자열을 반환합니다. (Object에서 상속됨)
Protected 메서드 Verify 인프라입니다.

위쪽

명시적 인터페이스 구현

  이름 설명
명시적 인터페이스 구현Private 메서드 _Attribute.GetIDsOfNames 이름 집합을 해당하는 디스패치 식별자 집합에 매핑합니다. (Attribute에서 상속됨)
명시적 인터페이스 구현Private 메서드 _Attribute.GetTypeInfo 인터페이스의 형식 정보를 가져오는 데 사용할 수 있는 개체의 형식 정보를 검색합니다. (Attribute에서 상속됨)
명시적 인터페이스 구현Private 메서드 _Attribute.GetTypeInfoCount 개체에서 제공하는 형식 정보 인터페이스의 수를 검색합니다(0 또는 1). (Attribute에서 상속됨)
명시적 인터페이스 구현Private 메서드 _Attribute.Invoke 개체에서 노출하는 메서드와 속성에 대한 액세스를 제공합니다. (Attribute에서 상속됨)

위쪽

설명

자신의 예상되는 예외 확인을 구현합니다. ExpectedExceptionAttribute 클래스의 기본 제공 메서드를 처리할 수 없는 추가 정보 및 요구 사항을 다음과 같이 지정할 수 있습니다.

  • 예외 상태 확인.

  • 하나 이상의 예외 형식 예상.

  • 잘못된 형식의 예외가 throw될 때 사용자 지정 메시지 표시

  • 네거티브 테스트 결과 제어

  • 특성을 사용하는 방법에 대한 자세한 내용은 특성을 사용하여 메타데이터 확장을 참조하십시오.

예제

다음 클래스에는 테스트할 메서드가 포함되어 있습니다.

using System;

namespace CSExample
{
    public class DivisionClass
    {
        private int fraction;

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

다음 사용자 지정 특성 클래스인 ExpectedArithmeticException은 예외 형 및 메시지를 확인하는 ExpectedExceptionBaseAttribute 클래스에서 파생됩니다. ExpectedArithmeticException 특성은 테스트 메서드가 System.ArithmeticException인 형식의 예외를 throw하는지, System.ArithmeticException에서 파생되는지를 확인합니다. 또한 예외 메시지가 지정된 예외 메시지와 일치하는지를 확인합니다. 단위 테스트는 DivideByZeroException을 throw하기 때문에 통과합니다. 이 경우 ArithmeticException에서 파생되고 지정한 예외 메시지는 단위 테스트로 throw되는 예외 메시지와 일치합니다.

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);
        }

    }
}

스레드로부터의 안전성

이 형식의 모든 공용 static(Visual Basic의 경우 Shared) 멤버는 스레드로부터 안전합니다. 인터페이스 멤버는 스레드로부터 안전하지 않습니다.

참고 항목

참조

Microsoft.VisualStudio.TestTools.UnitTesting 네임스페이스