目标
我想要一个解决方案,其中包括一个 SQL Server 数据库项目和一个单元测试项目。 (+集成测试项目?)
该解决方案将由 azure devops 上的 git 存储库进行源代码控制,理想情况下,我希望有一个启动 LocalDB (mssqllocaldb) 数据库、运行数据库项目的脚本/datpac 的管道,以获取它加快速度,然后运行单元测试,这些测试应该能够访问本地服务器上新创建的数据库。到目前为止我得到了什么
我正在尝试的测试相当简单:(当前使用 dapper,一旦我可以让这个测试工作,它将与连接字符串一起移动到 api 项目):
[TestMethod]
public void TestDBConnection()
{
var connString = "Server=(localdb)\\mssqllocaldb;Database=custom_db_name_here;Trusted_Connection=True;";
using (var connection = new SqlConnection(connString))
{
var result = connection.Query<int>(sql: "select 1", commandType: CommandType.Text);
Assert.AreEqual(result.Count(), 1);
Assert.AreEqual(result.FirstOrDefault(), 1);
}
}
我对 devops 没有太多经验,这是 azure devops 生成的 yaml 文件,我添加了 start mssqllocaldb
任务。
trigger:
- master
pool:
vmImage: 'windows-latest'
variables:
solution: '**/*.sln'
buildPlatform: 'Any CPU'
buildConfiguration: 'Release'
steps:
- task: NuGetToolInstaller@1
- task: NuGetCommand@2
inputs:
restoreSolution: '$(solution)'
- task: VSBuild@1
inputs:
solution: '$(solution)'
msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:DesktopBuildPackageLocation="$(build.artifactStagingDirectory)\WebApp.zip" /p:DeployIisAppPath="Default Web Site"'
platform: '$(buildPlatform)'
configuration: '$(buildConfiguration)'
- task: PowerShell@2
displayName: 'start mssqllocaldb'
inputs:
targetType: 'inline'
script: 'sqllocaldb start mssqllocaldb'
# Publish probably goes here, not sure how though?
- task: VSTest@2
inputs:
platform: '$(buildPlatform)'
configuration: '$(buildConfiguration)'
问题
我不知道如何创建新数据库,添加所有结构(表、过程等)和数据。
最佳答案
使用 FluentMigrator(dacpac 方法的替代方法)
由于您使用的是 dapper,我建议您使用 FluentMigrator管理您的迁移。当您在长时间运行的环境(例如产品)中管理迁移时,这将派上用场。
您可以采用两种方法来构建和播种数据库以进行测试。这两个选项实际上只是使用 FluentMigrator 应用迁移的两种方式:进程内和进程外。
选项 1:作为测试初始化的一部分,进程中(我个人的偏好)
看来您正在使用 MSTest 框架,因此您需要放入运行迁移脚本并播种任何数据的 [AssemblyInitialize]
代码。由于您为测试播种的数据并不打算播种到产品中,因此我会将其与迁移脚本分开。 FluentMigrator 使您能够在进程中运行迁移(即从 C# 代码)。您可以在FluentMigrator quickstart guide中找到详细信息
使用这种方法,您的管道将不需要更改。这样做的另一个优点是,任何想要搭建本地数据库的开发人员都可以在启动本地数据库后简单地运行测试套件。
根据我的经验,即使我会使用它来构建数据库进行测试,我仍然使用进程外方法将迁移应用到长时间运行的环境。
选项 2:作为管道中的单独任务,在进程外
这是您可以在FluentMigrator quickstart guide中找到的另一个选项。 。使用此选项,您可以在启动 LocalDB 后创建一个任务来运行迁移。我不喜欢这种方法,因为当您在本地开发时,您必须通过运行命令来知道何时应用迁移,这很乏味。
使用 SqlPackage(dacpac 方法)
Azure Hosted Agents provide SqlPackage默认情况下,构建 .dacpac
文件后,请将以下任务添加到管道中,确保更新生成的 dacpac 的路径/名称
- script: SqlPackage /Action:Import /SourceFile:"$(Build.Repository.LocalPath)\dbproject\bin
debug\project.dacpac" /TargetConnectionString:"Data Source=(localdb)\v11.0;Initial Catalog=devdb; Integrated Security=true;"
workingDirectory: C:\Program Files\Microsoft SQL Server\160\DAC\bin\
displayName: 'Import dacpac'
关于c# - Azure DevOps 测试数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76272901/