English
Test projects
Step 1. Why a real database
Why. Tests of a data layer are often written against EF Core's in-memory provider or SQLite, because they need no server. For Chatex both would be worthless, because most of what we want to prove happens inside PostgreSQL:
- the unique index on
direct_keyand the check constraintck_chats_direct_key; ILIKE … ESCAPE, a PostgreSQL feature;- the row-value comparison of the chat list cursor and the
ROW_NUMBER()of its projection; ExecuteUpdateAsyncinMarkReadAsync, which must not move a read position backwards;- transactions with rollback.
The in-memory provider has no constraints and no SQL at all; SQLite has different SQL. A test that passes there says nothing about production. So the tests run against the same PostgreSQL 18 as development and production, in a Docker container that each test run starts and throws away — the next chapter. Docker must be running for the tests.
Chatex uses three libraries for testing:
- xUnit v3 — the test framework: test classes,
[Fact]and[Theory]methods, fixtures, the runner; - Shouldly — readable assertions:
count.ShouldBe(3)instead ofAssert.Equal(3, count), and a failure message that quotes the expression that failed; - Testcontainers and Respawn — a database container per run and a fast reset between tests.
Step 2. Create the projects
Why. The tests live in the folder Tests/, next to Source/. Two projects are needed now:
Chatex.Testing— a plain library with the infrastructure: the database container and the base class of database tests. The business and API tests of later topics use it too.Chatex.Data.Tests— the tests of the data layer. Each layer gets its own test project (Chatex.Core.Testsin topic 7,Chatex.Api.Testsin topic 12).
Do.
powershell
dotnet new classlib -o Tests/Chatex.Testingpowershell
dotnet new classlib -o Tests/Chatex.Data.Testspowershell
Remove-Item Tests/Chatex.Testing/Class1.cs, Tests/Chatex.Data.Tests/Class1.cspowershell
dotnet sln add Tests/Chatex.Testing Tests/Chatex.Data.TestsBoth projects test or support the data layer, so they reference it:
powershell
dotnet add Tests/Chatex.Testing reference Source/Chatex.Datapowershell
dotnet add Tests/Chatex.Data.Tests reference Source/Chatex.DataThe infrastructure library needs three packages:
powershell
dotnet add Tests/Chatex.Testing package Testcontainers.PostgreSqlpowershell
dotnet add Tests/Chatex.Testing package Respawnpowershell
dotnet add Tests/Chatex.Testing package xunit.v3.extensibility.corexunit.v3.extensibility.core gives the library the interfaces of xUnit (IAsyncLifetime, TestContext) without making it a test project. As in topic 2, remove the <PropertyGroup> that the template wrote into both .csproj files; the projects then look like this:
xml
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\..\Source\Chatex.Data\Chatex.Data.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Respawn" />
<PackageReference Include="Testcontainers.PostgreSql" />
<PackageReference Include="xunit.v3.extensibility.core" />
</ItemGroup>
</Project>xml
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\..\Source\Chatex.Data\Chatex.Data.csproj" />
</ItemGroup>
</Project>The test project lists only what it tests. Everything a test project needs besides that comes from one shared file.
Step 3. Settings for every test project
Why. Each test project needs the same things: to be an executable (xUnit v3 test projects are programs), the xUnit, Shouldly and test SDK packages, the infrastructure library, the same global using directives. A Directory.Build.props in the folder Tests/ gives them to every project below it.
There is a catch. MSBuild imports only the nearest Directory.Build.props above a project. A file in Tests/ would hide the one in the repository root with its strict settings from topic 2 — unless it imports that file itself, which is what its first line does.
Do. Create Tests/Directory.Build.props:
xml
<Project>
<Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Build.props', '$(MSBuildThisFileDirectory)../'))" />
<!-- Settings shared by the test projects (*.Tests); Chatex.Testing is a plain library. -->
<PropertyGroup Condition="$(MSBuildProjectName.EndsWith('.Tests'))">
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup Condition="$(MSBuildProjectName.EndsWith('.Tests'))">
<!-- One database per test assembly, so tests in an assembly must not run in parallel. -->
<Content Include="$(MSBuildThisFileDirectory)xunit.runner.json" Link="xunit.runner.json" CopyToOutputDirectory="PreserveNewest" />
<Using Include="Shouldly" />
<Using Include="Xunit" />
<Using Include="Chatex.Testing" />
<ProjectReference Include="$(MSBuildThisFileDirectory)Chatex.Testing/Chatex.Testing.csproj" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="Shouldly" />
<PackageReference Include="xunit.runner.visualstudio">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="xunit.v3" />
</ItemGroup>
</Project>GetPathOfFileAbovefinds the nextDirectory.Build.propsabove theTestsfolder — the one in the root — and imports it. All test projects keep warnings-as-errors, nullable and the analyzers.- The condition
$(MSBuildProjectName.EndsWith('.Tests'))applies the test settings only to projects whose names end with.Tests.Chatex.Testingstays a plain library; naming decides what is a test project. OutputTypeExe— xUnit v3 builds every test project into a program that runs its own tests. Together with the setting"test": { "runner": "Microsoft.Testing.Platform" }inglobal.jsonfrom topic 2,dotnet testruns these programs on the new Microsoft Testing Platform.<Using Include="..." />adds globalusingdirectives: every test file can useShould…,[Fact]and the infrastructure without writing theusinglines.- The project reference to
Chatex.Testingand the four packages are added to every test project.
Next to it, create the runner settings that the props file copies into every test project:
json
{
"$schema": "https://xunit.net/schema/current/xunit.runner.schema.json",
"parallelizeTestCollections": false
}By default xUnit runs test classes in parallel. All tests of a project share one database that is wiped before each test, so two tests running at the same time would wipe each other's data. Turning off parallel collections makes the tests of one project run one after another; the different test projects still run in parallel, each with its own database container.
Chatex.slnx now has a /Tests/ folder with both projects. A build at this point fails, and the error is instructive:
error CS0234: The type or namespace name 'Testing' does not exist in the namespace 'Chatex'The global using Chatex.Testing refers to a namespace that has no types yet — an empty library defines no namespaces. The next chapter fills it, and the build succeeds again.