다음을 통해 공유


연습: 사용자 지정 테스트 조건을 사용하여 저장 프로시저 결과 확인

이 기능 확장 연습에서는 테스트 조건을 만들고 SQL Server 단위 테스트를 만들어 해당 기능을 확인합니다. 이 프로세스에는 테스트 조건에 대한 클래스 라이브러리 프로젝트를 만들고 이 프로젝트를 서명 및 설치하는 작업이 포함됩니다. 업데이트하려는 테스트 조건이 이미 있는 경우 방법: 이전 릴리스에서 SQL Server Data Tools로 Visual Studio 2010 사용자 지정 테스트 조건 업그레이드를 참조하세요.

이 연습에서는 다음 작업을 수행합니다.

  • 테스트 조건 만들기

  • 강력한 이름으로 어셈블리에 서명하는 방법입니다.

  • 프로젝트에 필요한 참조를 추가하는 방법입니다.

  • 테스트 조건을 빌드하는 방법입니다.

  • 새 테스트 조건을 설치하는 방법입니다.

  • 새 테스트 조건을 테스트하는 방법입니다.

이 연습을 완료하려면 최신 버전의 SQL Server Data Tools가 포함된 Visual Studio 2010 또는 Visual Studio 2012가 있어야 합니다. 자세한 내용은 SQL Server Data Tools 설치를 참조하세요.

사용자 지정 테스트 조건 만들기

먼저 클래스 라이브러리를 만듭니다.

  1. 파일 메뉴에서 새로 만들기 를 클릭한 다음 프로젝트를 클릭합니다.

  2. 새 프로젝트 대화 상자의 프로젝트 형식에서 Visual C#을 클릭합니다.

  3. 템플릿에서 클래스 라이브러리를 선택합니다.

  4. 이름 텍스트 상자에 ColumnCountCondition을 입력한 다음 확인을 클릭합니다.

다음으로 프로젝트에 서명합니다.

  1. 프로젝트 메뉴에서 ColumnCountCondition 속성을 클릭합니다.

  2. 서명 탭에서 어셈블리 서명 확인란을 선택합니다.

  3. 강력한 이름 키 파일 선택 상자에서 <새로 만들기...>를 클릭합니다.

    강력한 이름 키 만들기 대화 상자가 나타납니다.

  4. 키 파일 이름 상자에 SampleKey를 입력합니다.

  5. 암호를 입력하고 확인을 위해 한 번 더 입력한 후 확인을 클릭합니다. 솔루션을 빌드할 때 이 키 파일이 어셈블리에 서명하는 데 사용됩니다.

  6. 파일 메뉴에서 모두 저장을 클릭합니다.

  7. 빌드 메뉴에서 솔루션 빌드를 클릭합니다.

다음으로 프로젝트에 필요한 참조를 추가합니다.

  1. 솔루션 탐색기에서 ColumnCountCondition 프로젝트를 선택합니다.

  2. 프로젝트 메뉴에서 참조 추가를 클릭하여 참조 추가 대화 상자를 표시합니다.

  3. .NET 탭을 선택합니다.

  4. 구성 요소 이름 열에서 System.ComponentModel.Composition 구성 요소를 찾아 선택합니다. 구성 요소를 선택한 후 확인을 클릭합니다.

  5. 필요한 어셈블리 참조를 추가합니다. 프로젝트 노드를 마우스 오른쪽 단추로 클릭한 다음 참조 추가를 클릭합니다. 찾아보기를 선택하고 C:\Program Files (x86)\Microsoft SQL Server\110\DAC\Bin 폴더로 이동합니다. Microsoft.Data.Tools.Schema.Sql.dll을 닫고 추가를 클릭한 다음 확인을 클릭합니다.

  6. 프로젝트 메뉴에서 프로젝트 언로드를 클릭합니다.

  7. 솔루션 탐색기에서 프로젝트를 마우스 오른쪽 단추로 클릭하고 편집 <프로젝트 이름>.csproj를 선택합니다.

  8. Microsoft.CSharp.targets 가져오기 뒤에 다음 Import 문을 추가합니다.

    <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\SSDT\Microsoft.Data.Tools.Schema.Sql.UnitTesting.targets" Condition="'$(VisualStudioVersion)' == ''" />  
    
    <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\SSDT\Microsoft.Data.Tools.Schema.Sql.UnitTesting.targets" Condition="'$(VisualStudioVersion)' != ''" />  
    
  9. 파일을 저장하고 닫습니다. 솔루션 탐색기에서 프로젝트를 마우스 오른쪽 단추로 클릭하고 프로젝트 다시 로드를 선택합니다.

    솔루션 탐색기에서 프로젝트의 참조 노드 아래에 필요한 참조가 표시됩니다.

ResultSetColumnCountCondition 클래스 만들기

이제 Class1의 이름을 ResultSetColumnCountCondition으로 바꾸고 testcondition에서 파생합니다. ResultSetColumnCountCondition 클래스는 ResultSet에서 반환된 열 수를 확인하는 간단한 테스트 조건입니다. 이 조건을 사용하여 저장 프로시저에 대한 계약이 올바른지 확인할 수 있습니다.

  1. 솔루션 탐색기에서 Class1.cs를 마우스 오른쪽 단추로 클릭하고 이름 바꾸기를 클릭한 다음 ResultSetColumnCountCondition.cs를 입력합니다.

  2. 를 클릭하여 모든 참조의 이름을 Class1로 바꾸도록 확인합니다.

  3. ResultSetColumnCountCondition.cs 파일을 열고 문을 사용하여 다음을 파일에 추가합니다.

    using System;  
    using System.ComponentModel;  
    using System.Data;  
    using System.Data.Common;  
    using Microsoft.Data.Tools.Schema.Sql.UnitTesting;  
    using Microsoft.Data.Tools.Schema.Sql.UnitTesting.Conditions;  
    
    namespace ColumnCountCondition {  
        public class ResultSetColumnCountCondition  
    
  4. testcondition에서 클래스를 파생합니다.

    public class ResultSetColumnCountCondition : TestCondition  
    
  5. ExportTestConditionAttribute를 추가합니다. UnitTesting.Conditions.ExportTestConditionAttribute에 대한 자세한 내용은 방법: SQL Server 단위 테스트 디자이너용 테스트 조건 만들기를 참조하세요.

    [ExportTestCondition("ResultSet Column Count", typeof(ResultSetColumnCountCondition))]  
        public class ResultSetColumnCountCondition : TestCondition  
    
  6. 멤버 변수 및 생성자를 만듭니다.

            private int _resultSet;  
            private int _count;  
            private int _batch;  
    
            public ResultSetColumnCountCondition() {  
                _resultSet = 1;  
                _count = 0;  
                _batch = 1;  
            }  
    
  7. Assert 어설션을 메서드를 재정의합니다. 이 메서드에는 데이터베이스에 대한 연결을 나타내는 IDbConnectionSqlExecutionResult에 대한 인수가 포함됩니다. 이 메서드는 오류 처리에 DataSchemaException을 사용합니다.

           //method you need to override  
            //to perform the condition verification  
            public override void Assert(DbConnection validationConnection, SqlExecutionResult[] results)  
            {  
                //call base for parameter validation  
                base.Assert(validationConnection, results);  
    
                //verify batch exists  
                if (results.Length < _batch)  
                    throw new DataException(String.Format("Batch {0} does not exist", _batch));  
    
                SqlExecutionResult result = results[_batch - 1];  
    
                //verify resultset exists  
                if (result.DataSet.Tables.Count < ResultSet)  
                    throw new DataException(String.Format("ResultSet {0} does not exist", ResultSet));  
    
                DataTable table = result.DataSet.Tables[ResultSet - 1];  
    
                //actual condition verification  
                //verify resultset column count matches expected  
                if (table.Columns.Count != Count)  
                    throw new DataException(String.Format(  
                        "ResultSet {0}: {1} columns did not match the {2} columns expected",  
                        ResultSet, table.Columns.Count, Count));  
            }  
    
    Add the following method, which overrides the ToString method:  
    C#  
            //this method is called to provide the string shown in the  
            //test conditions panel grid describing what the condition tests  
            public override string ToString()  
            {  
                return String.Format(  
                    "Condition fails if ResultSet {0} does not contain {1} columns",  
                    ResultSet, Count);  
            }  
    
  8. CategoryAttribute, DisplayNameAttributeDescriptionAttribute 특성을 사용하여 다음 테스트 조건 속성을 추가합니다.

            //below are the test condition properties  
            //that are exposed to the user in the property browser  
            #region Properties  
    
            //property specifying the resultset for which  
            //you want to check the column count  
            [Category("Test Condition")]  
            [DisplayName("ResultSet")]  
            [Description("ResultSet Number")]  
            public int ResultSet  
            {  
                get { return _resultSet; }  
    
                set  
                {  
                    //basic validation  
                    if (value < 1)  
                        throw new ArgumentException("ResultSet cannot be less than 1");  
    
                    _resultSet = value;  
                }  
            }  
    
            //property specifying  
            //expected column count  
            [Category("Test Condition")]  
            [DisplayName("Count")]  
            [Description("Column Count")]  
            public int Count  
            {  
                get { return _count; }  
    
                set  
                {  
                    //basic validation  
                    if (value < 0)  
                        throw new ArgumentException("Count cannot be less than 0");  
    
                    _count = value;  
                }  
            }  
             #endregion  
    

최종 코드 목록은 다음과 같습니다.

using System;  
using System.ComponentModel;  
using System.Data;  
using System.Data.Common;  
using Microsoft.Data.Tools.Schema.Sql.UnitTesting;  
using Microsoft.Data.Tools.Schema.Sql.UnitTesting.Conditions;  
  
namespace ColumnCountCondition  
{  
  
    [ExportTestCondition("ResultSet Column Count", typeof(ResultSetColumnCountCondition))]  
    public class ResultSetColumnCountCondition : TestCondition  
    {  
        private int _resultSet;  
        private int _count;  
        private int _batch;  
  
        public ResultSetColumnCountCondition()  
        {  
            _resultSet = 1;  
            _count = 0;  
            _batch = 1;  
        }  
  
        //method you need to override  
        //to perform the condition verification  
        public override void Assert(DbConnection validationConnection, SqlExecutionResult[] results)  
        {  
            //call base for parameter validation  
            base.Assert(validationConnection, results);  
  
            //verify batch exists  
            if (results.Length < _batch)  
                throw new DataException(String.Format("Batch {0} does not exist", _batch));  
  
            SqlExecutionResult result = results[_batch - 1];  
  
            //verify resultset exists  
            if (result.DataSet.Tables.Count < ResultSet)  
                throw new DataException(String.Format("ResultSet {0} does not exist", ResultSet));  
  
            DataTable table = result.DataSet.Tables[ResultSet - 1];  
  
            //actual condition verification  
            //verify resultset column count matches expected  
            if (table.Columns.Count != Count)  
                throw new DataException(String.Format(  
                    "ResultSet {0}: {1} columns did not match the {2} columns expected",  
                    ResultSet, table.Columns.Count, Count));  
        }  
  
        //this method is called to provide the string shown in the  
        //test conditions panel grid describing what the condition tests  
        public override string ToString()  
        {  
            return String.Format(  
                "Condition fails if ResultSet {0} does not contain {1} columns",  
                ResultSet, Count);  
        }  
  
        //below are the test condition properties  
        //that are exposed to the user in the property browser  
        #region Properties  
  
        //property specifying the resultset for which  
        //you want to check the column count  
        [Category("Test Condition")]  
        [DisplayName("ResultSet")]  
        [Description("ResultSet Number")]  
        public int ResultSet  
        {  
            get { return _resultSet; }  
  
            set  
            {  
                //basic validation  
                if (value < 1)  
                    throw new ArgumentException("ResultSet cannot be less than 1");  
  
                _resultSet = value;  
            }  
        }  
  
        //property specifying  
        //expected column count  
        [Category("Test Condition")]  
        [DisplayName("Count")]  
        [Description("Column Count")]  
        public int Count  
        {  
            get { return _count; }  
  
            set  
            {  
                //basic validation  
                if (value < 0)  
                    throw new ArgumentException("Count cannot be less than 0");  
  
                _count = value;  
            }  
        }  
  
        #endregion  
    }  
}  
  

다음으로 프로젝트를 빌드합니다.

프로젝트 컴파일 및 테스트 조건 설치하기

빌드 메뉴에서 솔루션 빌드를 클릭합니다.

다음으로 어셈블리 정보를 확장 디렉터리에 복사합니다. Visual Studio는 시작 시 %Program Files%\Microsoft Visual Studio <Version>\Common7\IDE\Extensions\Microsoft\SQLDB\TestConditions 디렉터리 및 하위 디렉터리에 있는 모든 확장을 확인하고 이를 사용할 수 있도록 합니다.

출력 디렉터리의 ColumnCountCondition.dll 어셈블리 파일을 %Program Files%\Microsoft Visual Studio <Version>\Common7\IDE\Extensions\Microsoft\SQLDB\TestConditions 디렉터리에 복사합니다.

기본적으로 컴파일된 .dll 파일의 경로는 YourSolutionPath\YourProjectPath\bin\Debug 또는 YourSolutionPath\YourProjectPath\bin\Release입니다.

다음으로 새 Visual Studio 세션을 시작하고 데이터베이스 프로젝트를 만듭니다. 새 Visual Studio 세션을 시작하고 데이터베이스 프로젝트를 만들려면:

  1. Visual Studio의 두 번째 세션을 시작합니다.

  2. 파일 메뉴에서 새로 만들기 를 클릭한 다음 프로젝트를 클릭합니다.

  3. 새 프로젝트 대화 상자의 설치된 템플릿 목록에서 SQL Server 노드를 선택합니다.

  4. [세부 정보] 창에서 SQL Server 데이터베이스 프로젝트를 클릭합니다.

  5. 이름 텍스트 상자에 SampleConditionDB를 입력하고 확인을 클릭합니다.

다음으로 단위 테스트를 만들어야 합니다. 새 테스트 클래스 내에 SQL Server 단위 테스트를 만들려면:

  1. 테스트 메뉴에서 새 테스트를 클릭하여 새 테스트 추가 대화 상자를 표시합니다.

    솔루션 탐색기에서 테스트 프로젝트를 마우스 오른쪽 단추로 클릭하고 추가를 가리킨 다음 새 테스트를 클릭할 수도 있습니다.

  2. 템플릿 목록에서 SQL Server 단위 테스트를 클릭합니다.

  3. 테스트 이름SampleUnitTest를 입력합니다.

  4. 테스트 프로젝트에 추가에서 새 Visual C# 테스트 프로젝트 만들기를 클릭합니다. 그런 다음 확인을 클릭하여 새 테스트 프로젝트 대화 상자를 표시합니다.

  5. 프로젝트 이름에 SampleUnitTest를 입력합니다.

  6. 취소를 클릭하여 데이터베이스 연결을 사용하도록 테스트 프로젝트를 구성하지 않고 SQL Server 단위 테스트를 만듭니다. 빈 테스트가 SQL Server 단위 테스트 디자이너에 나타납니다. Visual C# 소스 코드 파일이 테스트 프로젝트에 추가됩니다.

    데이터베이스 연결이 포함된 데이터베이스 단위 테스트를 만들고 구성하는 방법에 대한 자세한 내용은 방법: 빈 SQL Server 단위 테스트 만들기를 참조하세요.

  7. 단위 테스트 만들기를 완료하려면 여기를 클릭하여 생성을 클릭하세요. SQL Server 프로젝트에서 새 테스트 조건을 확인할 수 있습니다.

참고 항목

기존 단위 테스트 프로젝트에서 사용자 지정 테스트 조건을 사용하려면 하나 이상의 새 SQL Server 단위 테스트 클래스를 만들어야 합니다. 테스트 클래스를 만드는 동안 테스트 조건 어셈블리에 대한 필요한 참조가 테스트 프로젝트에 추가됩니다.

새 테스트 조건을 보려면

  1. SQL Server 단위 테스트 디자이너테스트 조건에 있는 이름 열에서 inconclusiveCondition1 테스트를 클릭합니다.

  2. 테스트 조건 삭제 도구 모음 단추를 클릭하여 inconclusiveCondition1 테스트를 제거합니다.

  3. 테스트 조건 드롭다운을 클릭하고 결과 집합 열 개수를 선택합니다.

  4. 테스트 조건 추가 도구 모음 단추를 클릭하여 사용자 지정 테스트 조건을 추가합니다.

  5. 속성 창에서 Count, Enabled 및 ResultSet 속성을 구성합니다.

    자세한 내용은 방법: SQL Server 단위 테스트에 테스트 조건 추가를 참조하세요.

참고 항목

SQL Server 단위 테스트의 사용자 지정 테스트 조건