首页 > 解决方案 > Visual Studio: Load SQL file from SQL Studio Unit Test

问题描述

I am trying to set up a Microsoft Visual Studio Unit Testing environment for some of my SQL queries. My scenario is somewhat backwards to the typical software development scenario. For any given work product that I work on, I am trying to exercise ONE query through different scenarios, by passing in different parameters and comparing results.

My intention is to load my SQL query from a .sql file in each of my unit tests.

How do I open my SQL file for reading from within my SqlServerUnitTest1.cs file?

标签: visual-studio-2013sql-server-data-tools

解决方案


解决这个问题很复杂,所以我将描述我所做的大致轮廓。其中一些可能是不必要的,但至少我的说明将帮助您理解所有重要步骤:

  1. 创建一个新的解决方案,并在其中创建一个新的单元测试项目。(如果您像我一样使用 Reporting Services,请在其旁边创建一个 Reporting 项目)
  2. 将查询导入您的测试项目,并将属性设置为“Copy if Newer”或“Always Copy”。
  3. 在测试中加载 SQL 文件。我写了一个形式的函数:

.

public static string LoadSqlFile(string name)
{
  string path = Path.Combine( Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
                            , @"sql\" +  name
                            );

  return File.ReadAllText(path);
}

它通过文件名加载 SQL 文件。这是我的具体问题的答案。

  1. 编写测试(使用 UnitTest 模板,而不是 SqlServerUnitTest 模板)。我编写了一些代码来从 JSON 生成测试,这使得我团队中的非 C# 用户更容易做到这一点。在我的用例中,每个测试都有一个未声明的参数,该参数被传递给测试。JSON 还包含一个预期结果列表,我们将其与结果进行比较。

推荐阅读