Microsoft SQL Server
Microsoft SQL Server, also known as MSSQL, is a relational database engine developed by Microsoft and is a popular choice in enterprise systems. The following example provides .NET developers with a starting point to use a Microsoft SQL Server instance in the xUnit tests.
The following example uses the following NuGet packages:
dotnet add package Testcontainers.MsSql
dotnet add package Microsoft.Data.SqlClient
dotnet add package xunit
IDEs and editors may also require the following packages to run tests: xunit.runner.visualstudio
and Microsoft.NET.Test.Sdk
.
Copy and paste the following code into a new .cs
test file within an existing test project.
using Microsoft.Data.SqlClient;
using Testcontainers.MsSql;
using Xunit;
namespace TestcontainersModules;
public class MsSqlServerContainerTest : IAsyncLifetime
{
private readonly MsSqlContainer msSqlContainer
= new MsSqlBuilder()
.Build();
[Fact]
public async Task ReadFromMsSqlDatabase()
{
await using var connection = new SqlConnection(msSqlContainer.GetConnectionString());
await connection.OpenAsync();
await using var command = connection.CreateCommand();
command.CommandText = "Select 1;";
var actual = await command.ExecuteScalarAsync() as int?;
Assert.Equal(expected: 1, actual: actual.GetValueOrDefault());
}
public Task InitializeAsync()
=> msSqlContainer.StartAsync();
public Task DisposeAsync()
=> msSqlContainer.DisposeAsync().AsTask();
}
To execute the tests, use the command dotnet test
from a terminal.
A Note To Developers
Once Testcontainers creates a server instance, developers may use the connection string with any of the popular data-access technologies found in the .NET Ecosystem. Some of these libraries include Entity Framework Core, Dapper, and NHibernate. At which point, developers can execute database migrations and SQL scripts.