使用SSDT进行SQL单元测试(SQL Server数据工具)

In this article, we will discuss the essentials of the SQL unit testing and then we will explore how to apply SQL unit testing methodology in Azure SQL Database with help of SQL Server Data Tools (SSDT). In particular, this article will focus about unit test theory in terms of SQL Server database development aspect and illustrate SQL unit testing with a detailed example.

在本文中,我们将讨论SQL单元测试的要点,然后将探索如何借助SQL Server数据工具(SSDT)在Azure SQL数据库中应用SQL单元测试方法。 特别是,本文将从SQL Server数据库开发方面着重于单元测试理论,并通过一个详细的示例说明SQL单元测试。

单元测试: (Unit Test:)

Unit testing is used to check basis functionality and behavior of the smallest and independent part (function, method or etc.) of the code blocks that performs certain operations. In modern software development approaches, unit testing plays a key-role because unit tests directly affects code quality. On the other hand, when we look at unit testing in terms of continuous integration and continuous development approach, the entire application code can be tested before the production deployment process with help of unit test methods. If any unit test returns fail, we can automatically cancel the deployment process.

单元测试用于检查执行某些操作的代码块的最小和独立部分(功能,方法等)的基本功能和行为。 在现代软件开发方法中,单元测试起着关键作用,因为单元测试直接影响代码质量。 另一方面,当我们从持续集成和持续开发方法的角度看待单元测试时,可以在生产部署过程之前借助单元测试方法对整个应用程序代码进行测试。 如果任何单元测试返回失败,我们可以自动取消部署过程。

数据库单元测试: (Database Unit Test:)

Now let’s review the basic concept of unit testing concept with a focus on SQL unit testing. The SQL unit testing approach allows us to test individual and programmable part of database objects such as stored procedures, functions, triggers and schema. The advantage of SQL unit testing is to develop more robust database designs, because these objects have already been checked before production deployment, so SQL unit testing process allows us to minimize the errors which are related to database objects. Assume that we are developing a stored procedure and we know that it will not return any rows, so we can configure a test condition to verify this behavior of the stored procedure and then it can be tested according to this condition as part of a review of the database, or latest database changes.

现在,让我们回顾一下单元测试概念的基本概念,重点是SQL单元测试。 SQL单元测试方法使我们可以测试数据库对象的各个部分和可编程部分,例如存储过程,函数,触发器和架构。 SQL单元测试的优点是开发更健壮的数据库设计,因为在生产部署之前已经检查了这些对象,因此SQL单元测试过程使我们能够最大程度地减少与数据库对象相关的错误。 假设我们正在开发一个存储过程,并且知道它不会返回任何行,那么我们可以配置一个测试条件以验证该存储过程的这种行为,然后可以根据此条件对其进行测试,作为对的回顾。数据库或最新数据库更改。

先决条件 (Prerequisites)

In this article we will use the following tools:

在本文中,我们将使用以下工具:

Visual Studio 2017: It is an integrated development environment (IDE) which allows us to develop various project types in different programing languages.

Visual Studio 2017 :这是一个集成开发环境(IDE),使我们可以使用不同的编程语言开发各种项目类型。

SQL Server Data Tools: It is also known as SSDT, another required tool to develop SQL unit testing projects. SSDT allows us to develop SQL Server database projects and it also provides Analysis Service, Reporting Service and Integration Service projects.

SQL Server数据工具 :也称为SSDT,这是开发SQL单元测试项目的另一个必需工具。 SSDT允许我们开发SQL Server数据库项目,还提供分析服务,报表服务和集成服务项目。

Azure SQL: It is a cloud based relational database that can be use database as a service so that we can use Azure SQL database without any physical hardware or on premise-installation.

Azure SQL :这是一个基于云的关系数据库,可以将数据库用作服务,因此我们可以使用Azure SQL数据库而无需任何物理硬件或在内部安装。

脚步 (Steps)

The following SQL unit testing demonstration will be completed in the below three phases:

下面SQL单元测试演示将在以下三个阶段中完成:

  1. Import Azure SQL Database to SQL Server Database Project: In this phase, we will connect to Azure SQL database and import Azure SQL database objects to database project 将Azure SQL数据库导入到SQL Server数据库项目:在此阶段,我们将连接到Azure SQL数据库并将Azure SQL数据库对象导入到数据库项目
  2. Add New Stored Procedure to SQL Server Database Project: In this phase, we will add a new stored procedure to database project 将新的存储过程添加到SQL Server数据库项目:在此阶段,我们将新的存储过程添加到数据库项目
  3. Create SQL Unit Testing: In this last phase, we will develop a SQL unit test project and then we will test a stored procedure which was added in the previous phase 创建SQL单元测试:在最后一个阶段,我们将开发一个SQL单元测试项目,然后测试上一个阶段中添加的存储过程。

将Azure SQL数据库架构导入到SSDT中SQL Server数据库项目 (Importing an Azure SQL Database Schema to a SQL Server Database Project in SSDT)

In this first step, we will launch Visual Studio and then add a new SQL Server Database Project in SSDT. We will give a name to our database project and then check Create directory for solution. After that click OK so that our database project will be saved to specified location. If you check Create new Git repository, it allows us to track and save our project into Git source control.

在第一步中,我们将启动Visual Studio,然后在SSDT中添加一个新SQL Server数据库项目。 我们将为数据库项目命名,然后选中“ 创建目录”以获取解决方案。 之后,单击“ 确定”,以便我们的数据库项目将保存到指定位置。 如果您选中创建新的Git存储库 ,它使我们可以跟踪项目并将其保存到Git源代码管理中。

使用SSDT进行SQL单元测试(SQL Server数据工具)_第1张图片

In the Solution Explorer window in SSDT, we will right click the database project name and select database import method in the context menu. In this option, Visual Studio allow us two types of database importing method option. First one is Data-tier Application option which is also known as dacpac. Dacpac is a zipped deployment package which contains the database schema and other database objects definitions in xml files. The most significant benefit of this package is portability so we can deploy our database to any SQL Server instance and also we can deploy dacpac file to Azure SQL. Another method is to connect to database and then import database schema and object definitions from database server. We don’t have Azure SQL database dacpac file therefore we will choose this method. Actually, importing database operation process reads database schema and other object definitions from the source database and then creates a dacpac file under bin folder of database project so that Visual Studio performs deployment process through this dacpac file.

在SSDT的“解决方案资源管理器”窗口中,我们将右键单击数据库项目名称,然后在上下文菜单中选择数据库导入方法。 在此选项中,Visual Studio允许我们两种类型的数据库导入方法选项。 第一个是数据层应用程序选项 也称为dacpac。 Dacpac是一个压缩的部署程序包,其中包含xml文件中的数据库模式和其他数据库对象定义。 该软件包最显着的好处是可移植性,因此我们可以将数据库部署到任何SQL Server实例,也可以将dacpac文件部署到Azure SQL。 另一种方法是连接到数据库,然后从数据库服务器导入数据库模式和对象定义。 我们没有Azure SQL数据库dacpac文件,因此我们将选择此方法。 实际上,导入数据库操作过程将从源数据库中读取数据库架构和其他对象定义,然后在数据库项目的bin文件夹下创建一个dacpac文件,以便Visual Studio通过该dacpac文件执行部署过程。

使用SSDT进行SQL单元测试(SQL Server数据工具)_第2张图片

In the Import Database screen, we will click Select Connection and then connect to Azure SQL database in SSDT with proper credentials.

在“导入数据库”屏幕中,我们将单击“ 选择连接” ,然后使用适当的凭据连接到SSDT中的Azure SQL数据库。

使用SSDT进行SQL单元测试(SQL Server数据工具)_第3张图片

We will navigate and expand Azure tab then fill the credential options of the database connection and then click Connect.

我们将导航并展开“ Azure”选项卡,然后填写数据库连接的凭据选项,然后单击“ 连接”

使用SSDT进行SQL单元测试(SQL Server数据工具)_第4张图片

And finally, everything is ready to start importing database schema and object definitions from source Azure SQL database to database project. We will click Start in SSDT to begin importing database schema process.

最后,一切准备就绪,可以开始将数据库架构和对象定义从源Azure SQL数据库导入数据库项目。 我们将在SSDT中单击“ 开始”以开始导入数据库架构过程。

使用SSDT进行SQL单元测试(SQL Server数据工具)_第5张图片

使用SSDT进行SQL单元测试(SQL Server数据工具)_第6张图片

As already we noted that, Visual Studio created a dacpac package under the bin folder and every schema and object details are stored in this file. You can also import this file manually into another database server. We will right click to project and then select Open Folder in File Explorer in SSDT.

如前所述,Visual Studio在bin文件夹下创建了一个dacpac包,每个架构和对象详细信息都存储在此文件中。 您也可以手动将此文件导入另一个数据库服务器。 我们将右键单击进行工程,然后在SSDT的File Explorer中选择Open Folder

使用SSDT进行SQL单元测试(SQL Server数据工具)_第7张图片

We will navigate to bin -> Debug folder in SSDT so that we can find out DACPAC package.

我们将导航到SSDT中的bin-> Debug文件夹,以便我们找到DACPAC软件包。

使用SSDT进行SQL单元测试(SQL Server数据工具)_第8张图片

Now, we will change the target database property of database project because we will deploy it to Azure SQL. Right click in the database project and then select Properties option in SSDT and then change the target platform to Microsoft Azure SQL Database V12

现在,我们将更改数据库项目的目标数据库属性,因为我们会将其部署到Azure SQL。 右键单击数据库项目,然后在SSDT中选择“ 属性”选项,然后将目标平台更改为Microsoft Azure SQL数据库V12

使用SSDT进行SQL单元测试(SQL Server数据工具)_第9张图片

We will rebuild project in order to check errors in the project and check on the output of the project.

我们将重建项目,以检查项目中的错误并检查项目的输出。

使用SSDT进行SQL单元测试(SQL Server数据工具)_第10张图片

在SSDT中向SQL Server数据库项目添加新的存储过程 (Adding a new stored procedure to SQL Server database project in SSDT)

In the solution explorer, all of the database objects will be imported after the schema importing.

在解决方案资源管理器中,所有数据库对象将在架构导入后导入。

使用SSDT进行SQL单元测试(SQL Server数据工具)_第11张图片

In this part, we will add a new stored procedure under SalesLT schema which inserts new a new row to ProductCategory table. Right click into stored procedure folder in the Solution Explorer panel in SSDT and then add new item.

在这一部分中,我们将在SalesLT模式下添加一个新的存储过程,该过程向ProductCategory表中插入新行。 右键单击SSDT的“解决方案资源管理器”面板中的存储过程文件夹,然后添加新项。

使用SSDT进行SQL单元测试(SQL Server数据工具)_第12张图片

Chose the Stored Procedure in the object list and then give a name to this stored procedure.

在对象列表中选择存储过程 ,然后为该存储过程命名。

使用SSDT进行SQL单元测试(SQL Server数据工具)_第13张图片

We will add the following script in order to create stored procedure.

我们将添加以下脚本以创建存储过程。

CREATE PROCEDURE [SalesLT].[SetProcductCat]
  @ParentProductCategoryId AS INT ,
  @Name AS VARCHAR(50)
  AS
  INSERT INTO SalesLT.ProductCategory (ParentProductCategoryID,Name)
  VALUES(@ParentProductCategoryId,@Name)

使用SSDT进行SQL单元测试(SQL Server数据工具)_第14张图片

Now, we will make our first publish to Azure SQL database. Right click in the project and then select Publish.

现在,我们将首次发布到Azure SQL数据库。 右键单击项目,然后选择发布

使用SSDT进行SQL单元测试(SQL Server数据工具)_第15张图片

Publish Database window in SSDT will be open. In this window, we can configure the target database connection and save this configuration through Create Profile option.

SSDT中的“发布数据库”窗口将打开。 在此窗口中,我们可以配置目标数据库连接,并通过“ 创建配置文件”选项保存此配置。

使用SSDT进行SQL单元测试(SQL Server数据工具)_第16张图片

When you click Create Profile button, Visual Studio automatically creates publish.xml file which stores the credentials and other options. When you double click this file Publish Database screen will be reappear.

单击“创建配置文件”按钮时,Visual Studio会自动创建publish.xml文件,该文件存储凭据和其他选项。 当您双击此文件时,将重新出现“发布数据库”屏幕。

使用SSDT进行SQL单元测试(SQL Server数据工具)_第17张图片

The publish operation will be completed successfully.

发布操作将成功完成。

使用SSDT进行SQL单元测试(SQL Server数据工具)_第18张图片

在SSDT中创建SQL单元测试 (Creating SQL Unit Testing in SSDT)

In this section, we will focus to how to create and configure SQL unit testing project with help of SSDT. In the previous parts we created a database project and then we added a new stored procedure. However, we don’t have any idea about this stored procedure functional behaviors. For this reason, we need to add unit test to check its behavior. In generally, SQL unit testing is based on three phases and these are;

在本节中,我们将重点介绍如何在SSDT的帮助下创建和配置SQL单元测试项目。 在前面的部分中,我们创建了一个数据库项目,然后添加了一个新的存储过程。 但是,我们对该存储过程的功能行为一无所知。 因此,我们需要添加单元测试来检查其行为。 通常,SQL单元测试基于三个阶段,分别是:

  1. Pre-Test: In this step we can check any required conditions before the test method. For our test, we will delete particular rows which we will insert later in unit test 预测试:在此步骤中,我们可以在测试方法之前检查所有必要条件。 对于我们的测试,我们将删除特定的行,稍后将在单元测试中插入这些行
  2. Test: In this step, we can specify and add the test conditions 测试:在这一步中,我们可以指定并添加测试条件
    • I want to add a tip in here, you have to add a well-defined and clear explanations comments to test method because this description will help other developers to figure out to main idea of the test method. On the other hand, a well-prepared test documentation will take a significant advantage during to unit test development process because it will be hand-guide of unit test
    • 我想在此处添加提示,您必须在测试方法中添加定义明确且清晰的解释注释,因为该描述将帮助其他开发人员弄清测试方法的主要思想。 另一方面,准备好的测试文档将在单元测试开发过程中发挥重要作用,因为它将成为单元测试的手工指南。
  3. Post-Test: In this step, we can specify required operations after the test method 测试后:在此步骤中,我们可以在测试方法之后指定所需的操作

Now, let’s return to our SQL unit testing demonstration. We will right click to stored procedure and click Create Unit Test which we created in the previous steps. In the Create Unit Tests screen we will give a name to unit test project and select programing language of the test project. We can select C# or Visual Basic in SSDT.

现在,让我们回到我们SQL单元测试演示。 我们将右键单击存储过程,然后单击在先前步骤中创建的创建单元测试 。 在创建单元测试屏幕中,我们将为单元测试项目命名并选择测试项目的编程语言。 我们可以在SSDT中选择C#或Visual Basic。

使用SSDT进行SQL单元测试(SQL Server数据工具)_第19张图片

After these steps, SQL Server Test Configuration screen will appear. In this screen we will specify the connection string for test project and also we will check to automatically deploy the database project before unit tests are run. This option allows us to deploy the database project before running unit test.

完成这些步骤后,将出现“ SQL Server测试配置”屏幕。 在此屏幕中,我们将指定测试项目的连接字符串,还将检查在运行单元测试之前自动部署数据库项目。 此选项使我们可以在运行单元测试之前部署数据库项目。

使用SSDT进行SQL单元测试(SQL Server数据工具)_第20张图片

This setting is stored into app.config file of test project so that you can edit this setting according to yourself.

此设置存储在测试项目的app.config文件中,以便您可以根据自己的需要编辑此设置。

使用SSDT进行SQL单元测试(SQL Server数据工具)_第21张图片

Visual Studio SSDT will automatically create a test template however we need to change this unit test method. We will develop the test method according to following sample test document.

Visual Studio SSDT将自动创建测试模板,但是我们需要更改此单元测试方法。 我们将根据以下样本测试文件开发测试方法。

使用SSDT进行SQL单元测试(SQL Server数据工具)_第22张图片

We will select Pre-test option in the test condition combobox then add the following query. We will also add a little definition regarding to test document.

我们将在测试条件组合框中选择“ 预测试”选项,然后添加以下查询。 我们还将为测试文件添加一些定义。

/*
If test values exist in the table  delete this values in Pre-Test
Test Values : 
@ParentProductCategoryId =14
@Name =NewProductCategory
 
*/
DECLARE @ParentProductCategoryId AS INT = 14
DECLARE @Name AS VARCHAR(50) = 'NewProductCategory' 
DELETE FROM SalesLT.ProductCategory WHERE ParentProductCategoryID=@ParentProductCategoryId
AND Name=@Name

使用SSDT进行SQL单元测试(SQL Server数据工具)_第23张图片

Visual Studio offers various predefined test conditions. These are:

Visual Studio提供了各种预定义的测试条件。 这些是:

Data Checksum: This test condition compares expected result and set row values and resultset values which returned from test. If this resultsets values don’t match it will be a fail.

数据校验和:此测试条件比较预期结果,并设置从测试返回的行值和结果集值。 如果此结果集值不匹配,将失败。

Empty ResultSet: This test condition expects empty result set if tested.

空结果:测试是否本测试条件预计结果为空。

Execution Time: This test condition compares the tested method execution time and expected execution time. If tested method execution time takes longer than the expected execution time, it will be fail. The default value of this test condition is 30 second.

执行时间:此测试条件将测试方法的执行时间与预期的执行时间进行比较。 如果经过测试的方法执行时间比预期的执行时间更长,则将失败。 此测试条件的默认值为30秒。

Expected Schema: This test condition compares expected result set schema (columns and data types) and result set schema which returned from test. If this resultsets schema don’t match, it will be fail.

预期架构:此测试条件将预期结果集架构(列和数据类型)与从测试返回的结果集架构进行比较。 如果此结果集架构不匹配,则将失败。

Not Empty ResultSet: This test condition expects non-empty result set from test method.

非空结果集此测试条件要求测试方法提供非空结果集。

Row Count: This test condition compares resultset row number and expected row number.

行数:此测试条件将结果集行号与预期行号进行比较。

Scalar Value: This test condition compares expected value to particular value which returns from test method. In this test method we can configure column number and row number. Now, we will change the combobox to Test.

标量值:此测试条件将期望值与从测试方法返回的特定值进行比较。 在此测试方法中,我们可以配置列号和行号。 现在,我们将组合框更改为Test

The test condition must be Row Count because we have to check to insert functionality. In the Row Count condition, the Row Count property must be set as 1.

测试条件必须为“行数”,因为我们必须检查插入功能。 在“行数”条件下,“行数”属性必须设置为1。

/*
Test SetProductCatUnitTest stored procedure with test values 
and then check the test values in SalesLT.ProductCategory
Test Values : 
@ParentProductCategoryId =14
@Name =NewProductCategory
*/
 
DECLARE @IdentityNum AS INT, @ParentProductCategoryId AS INT, @Name AS VARCHAR (50);
SELECT @IdentityNum = 0,
       @ParentProductCategoryId = 14,
       @Name = 'NewProductCategory';
EXECUTE  [SalesLT].[SetProcductCat] @ParentProductCategoryId, @Name;
SELECT @IdentityNum=@@IDENTITY ;
 
SELECT * from SalesLT.ProductCategory where ProductCategoryId=@IdentityNum
AND Name=@Name 
AND ParentProductCategoryId=@ParentProductCategoryId

使用SSDT进行SQL单元测试(SQL Server数据工具)_第24张图片

Lastly, we will add Post-Test method in SSDT and then delete the inserted values from table.

最后,我们将在SSDT中添加Post-Test方法,然后从表中删除插入的值。

/*
Delete test values in SalesLT.ProductCategory in Post-test
Test Values : 
@ParentProductCategoryId =14
@Name =NewProductCategory
 
*/
DECLARE @ParentProductCategoryId AS INT = 14
DECLARE @Name AS VARCHAR(50) = 'NewProductCategory' 
DELETE FROM SalesLT.ProductCategory WHERE ParentProductCategoryID=@ParentProductCategoryId
AND Name=@Name

使用SSDT进行SQL单元测试(SQL Server数据工具)_第25张图片

Let’s run our unit test. In Visual Studio SSDT you will find Test Menu or Test explorer so that you can run the unit test. Let’s use test explorer and then click Run All test method.

让我们运行我们的单元测试。 在Visual Studio SSDT中,您将找到“测试菜单”或“测试资源管理器”,以便可以运行单元测试。 让我们使用测试资源管理器,然后单击“运行所有测试方法”。

使用SSDT进行SQL单元测试(SQL Server数据工具)_第26张图片

At first, Visual Studio SSDT deploys the project to target database and then it will run unit test methods.

首先,Visual Studio SSDT将项目部署到目标数据库,然后它将运行单元测试方法。

使用SSDT进行SQL单元测试(SQL Server数据工具)_第27张图片

Now, we will add Expected Schema test condition to check result set column names and datatypes.

现在,我们将添加Expected Schema测试条件以检查结果集列名和数据类型。

We will add new test condition which is expected schema and then click Configuration (…) button in the properties of the expected schema test condition.

我们将添加新的测试条件,它是预期的架构,然后在预期的架构测试条件的属性中单击“ 配置(…)”按钮。

使用SSDT进行SQL单元测试(SQL Server数据工具)_第28张图片

We will click a Select Connection… and configure a database connection then we will set the expected resultset columns and datatypes through the following query. In this point, the main idea is to compare expected resultset schema with test method resultset schema. According to our stored procedure, inserted row columns and datatypes have to match any row of the SalesLT.ProductCategory table.

我们将单击“选择连接…”并配置数据库连接,然后通过以下查询设置期望的结果集列和数据类型。 在这一点上,主要思想是将预期结果集架构与测试方法结果集架构进行比较。 根据我们的存储过程,插入的行列和数据类型必须与SalesLT.ProductCategory表的任何行匹配。

We will use the following query in the query and then click Retrieve in SSDT.

我们将在查询中使用以下查询,然后单击“在SSDT中检索”

SELECT TOP 1 * FROM SalesLT.ProductCategory

使用SSDT进行SQL单元测试(SQL Server数据工具)_第29张图片

We will re-run the test so that click Run All.

我们将重新运行测试,以便单击“全部运行”。

使用SSDT进行SQL单元测试(SQL Server数据工具)_第30张图片

Finally, our all test method passed.

最终,我们所有的测试方法都通过了。

结论 (Conclusion)

In this article we mentioned about SQL unit testing in SSDT and also we learnt how to develop and run unit testing in Visual Studio. SQL unit testing implantation provides various advantages to us such as improve coding quality, reduce development costs and degrade the defects of database schema and objects.

在本文中,我们提到了SSDT中SQL单元测试,还学习了如何在Visual Studio中开发和运行单元测试。 SQL单元测试植入为我们提供了多种优势,例如,提高了编码质量,降低了开发成本并降低了数据库架构和对象的缺陷。

目录 (Table of contents)

SQL Unit Testing with SSDT (SQL Server Data Tools)
SQL unit testing with the tSQLt framework for beginners
SQL Unit testing with the tSQLt framework and SQL Server Database Project integration
SQL unit testing best practices
How to use fake tables in SQL unit testing?
How to use fake functions with SQL unit testing?
SQL Unit Testing Mocking Stored Procedures
SQL Unit Testing: Working with exceptions
使用SSDT进行SQL单元测试(SQL Server数据工具)
使用tSQLt框架SQL单元测试面向初学者
使用tSQLt框架和SQL Server Database Project集成进行SQL单元测试
SQL单元测试最佳实践
如何在SQL单元测试中使用假表?
如何在SQL单元测试中使用伪函数?
SQL单元测试模拟存储过程
SQL单元测试:使用异常

翻译自: https://www.sqlshack.com/sql-unit-testing-with-ssdt-sql-server-data-tools/

你可能感兴趣的:(数据库,单元测试,python,java,mysql)