English
The first tests
Step 1. A base class with seeding helpers
Why. Almost every test of the data layer needs users, chats and messages before it can test anything. Creating them inline would make each test 30 lines of setup and 3 lines of point. A base class for the data tests registers the data layer and offers short seeding helpers: CreateUserAsync("alice"), CreateChatAsync(ChatType.Direct, alice, [bob]), AddMessagesAsync(chat, alice, 120).
Do. Create the base class in Chatex.Data.Tests:
cs
using Chatex.Data.Abstractions;
using Chatex.Data.Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
// Tests share one database that is wiped before each test; xunit.runner.json turns off parallel runs.
[assembly: AssemblyFixture(typeof(PostgresFixture))]
namespace Chatex.Data.Tests;
/// <summary>Data access layer on a clean database, plus seeding helpers.</summary>
public abstract class DbTestBase(PostgresFixture fixture) : DatabaseTest(fixture)
{
protected override void ConfigureServices(IServiceCollection services, string connectionString) =>
services.AddData(connectionString, o => o.RootPath = StorageRoot);
protected async Task<User> CreateUserAsync(string userName)
{
await using var scope = NewScope();
var user = new User { UserName = userName, Email = $"{userName}@example.test" };
var result = await Get<UserManager<User>>(scope).CreateAsync(user, "Passw0rd!");
result.Succeeded.ShouldBeTrue(string.Join("; ", result.Errors.Select(e => e.Description)));
Get<IUserRepository>(scope).AddProfile(new UserProfile { UserId = user.Id, DisplayName = userName.ToUpperInvariant() });
await Get<IUnitOfWork>(scope).SaveChangesAsync(Ct);
return user;
}
protected async Task<Chat> CreateChatAsync(
ChatType type, User owner, IEnumerable<User> others, DateTimeOffset? lastActivityAt = null)
{
await using var scope = NewScope();
var othersList = others.ToList();
var chat = new Chat
{
Type = type,
Title = type == ChatType.Direct ? null : $"{type} chat",
DirectKey = type == ChatType.Direct ? Chat.MakeDirectKey(owner.Id, othersList.Single().Id) : null,
CreatedById = owner.Id,
LastActivityAt = lastActivityAt ?? default,
};
var ownerRole = type == ChatType.Direct ? ChatMemberRole.Member : ChatMemberRole.Owner;
var otherRole = type == ChatType.Channel ? ChatMemberRole.Subscriber : ChatMemberRole.Member;
chat.Members.Add(new ChatMember { UserId = owner.Id, Role = ownerRole });
foreach (var other in othersList)
{
chat.Members.Add(new ChatMember { UserId = other.Id, Role = otherRole });
}
Get<IChatRepository>(scope).Add(chat);
await Get<IUnitOfWork>(scope).SaveChangesAsync(Ct);
return chat;
}
/// <summary>Adds messages whose UUIDv7 ids are one millisecond apart, so their order is known.</summary>
protected async Task<List<Message>> AddMessagesAsync(Chat chat, User sender, int count)
{
await using var scope = NewScope();
var start = DateTimeOffset.UtcNow.AddMinutes(-count);
var messages = Enumerable.Range(0, count)
.Select(i => new Message
{
Id = Guid.CreateVersion7(start.AddMilliseconds(i)),
ChatId = chat.Id,
SenderId = sender.Id,
Body = $"message {i}",
})
.ToList();
var repository = Get<IMessageRepository>(scope);
messages.ForEach(repository.Add);
await Get<IUnitOfWork>(scope).SaveChangesAsync(Ct);
return messages;
}
}[assembly: AssemblyFixture(typeof(PostgresFixture))]registers the fixture of the previous chapter for the whole test project. xUnit creates it once and passes it to the constructor of every test class that asks for it — here through the primary constructorsDbTestBase(PostgresFixture fixture)andDatabaseTest(fixture).ConfigureServicesregisters the real data layer, with the test's temporary folder for files.- Each helper uses its own scope and saves before returning, exactly like a separate request would.
- Users are created through
UserManager, the way the application will create them, so that the normalised name and the security stamp are set as Identity expects. AddMessagesAsyncgives the messages ids exactly one millisecond apart withGuid.CreateVersion7(timestamp). In topic 3 we saw that ids created within the same millisecond have a random order; a paging test must know the order for certain.lastActivityAt ?? default— passingdefaultlets the interceptor stamp the time; a test that cares about the order of chats passes explicit times.
Step 2. The first test
Why. Our first test proves the most important rule of the data model: a pair of users can have only one direct chat, whatever order they come in. A good test reads like the rule it checks — the method name is the rule, with underscores between the words (the .editorconfig of topic 2 allows such names in Tests/).
Each test has three parts, separated by blank lines:
- Arrange — create the situation: two users and a direct chat between them;
- Act — do the one thing being tested: create the same chat the other way round;
- Assert — check the result: the save fails with our exception, naming the unique index.
Do. Create the test class with the first two tests:
cs
using Chatex.Data.Abstractions;
using Chatex.Data.Entities;
using Chatex.Data.Exceptions;
using Microsoft.EntityFrameworkCore;
using Npgsql;
namespace Chatex.Data.Tests;
public sealed class ChatRepositoryTests(PostgresFixture fixture) : DbTestBase(fixture)
{
[Fact]
public async Task A_pair_of_users_can_have_only_one_direct_chat()
{
var alice = await CreateUserAsync("alice");
var bob = await CreateUserAsync("bob");
await CreateChatAsync(ChatType.Direct, alice, [bob]);
var error = await Should.ThrowAsync<UniqueConstraintException>(() => CreateChatAsync(ChatType.Direct, bob, [alice]));
error.ConstraintName.ShouldBe("ix_chats_direct_key");
}
[Fact]
public async Task Only_direct_chats_have_a_direct_key()
{
var alice = await CreateUserAsync("alice");
var bob = await CreateUserAsync("bob");
await using var scope = NewScope();
Get<IChatRepository>(scope).Add(new Chat
{
Type = ChatType.Group,
Title = "group",
DirectKey = Chat.MakeDirectKey(alice.Id, bob.Id),
CreatedById = alice.Id,
});
var error = await Should.ThrowAsync<DbUpdateException>(() => Get<IUnitOfWork>(scope).SaveChangesAsync(Ct));
error.InnerException.ShouldBeOfType<PostgresException>().SqlState.ShouldBe(PostgresErrorCodes.CheckViolation);
}
}[Fact]marks a test method without parameters.async Tasktests are awaited by xUnit.Should.ThrowAsync<T>(() => …)runs the lambda and passes only if it throws aT; it returns the exception for further checks.ShouldBe,ShouldBeOfType<T>()are Shouldly's assertions, written as extension methods on the value being checked.ShouldBeOfType<T>()also returns the value cast toT, so the chain can continue with.SqlState.- The second test proves the check constraint of topic 4. It is not translated into our exception — only unique violations are — so the test expects EF Core's
DbUpdateExceptionwith the PostgreSQL error code inside.
Step 3. Run the tests
Do. Make sure Docker Desktop is running, then run all tests of the solution from the repository root:
powershell
dotnet test --solution Chatex.slnxThe first run downloads the postgres:18-alpine image if it is not on your computer yet (you have it from compose.yaml) and the small helper image of Testcontainers.
Check
The summary at the end:
Test run summary: Passed!
total: 2
failed: 0
succeeded: 2
skipped: 0While the tests run, docker ps in another terminal shows a second PostgreSQL container with a random port, next to your development database; after the run it is gone.
To run one project, one class or some methods, use the options of the Microsoft Testing Platform:
powershell
dotnet test --project Tests/Chatex.Data.Testspowershell
dotnet test --project Tests/Chatex.Data.Tests --filter-class "*ChatRepositoryTests"powershell
dotnet test --project Tests/Chatex.Data.Tests --filter-method "*direct_key*"IDEs run the same tests from their test explorer (Visual Studio: Test → Test Explorer; Rider: Unit Tests; VS Code: the Testing view of C# Dev Kit), with a button per test.
./Run.ps1 test --solution Chatex.slnx passes its options to dotnet test, and ./Run.ps1 clean works now that the folder Tests/ exists (Table 2.2 of topic 2).
Step 4. Watch a test fail
Why. A test you have never seen fail may not test anything — a missing await or a wrong assertion can make it pass forever. Break the code on purpose, once, and read what the failure tells you.
Do. In ChatConfiguration, comment out the unique index on the direct key:
cs
// builder.HasIndex(c => c.DirectKey).IsUnique();The tests apply the migrations, not the model, so the index is still created — the configuration and the migration now disagree. Run the tests: both pass. That is exactly the situation has-pending-model-changes exists for (topic 4):
powershell
dotnet ef migrations has-pending-model-changes --project Source/Chatex.DataIt reports changes. Now break the migration instead: restore the configuration, then in your *_InitialCreate.cs delete the migrationBuilder.CreateIndex(...) call for ix_chats_direct_key and run the first test:
powershell
dotnet test --project Tests/Chatex.Data.Tests --filter-method "*only_one_direct_chat*"Check
The test fails, and Shouldly says what it expected:
failed Chatex.Data.Tests.ChatRepositoryTests.A_pair_of_users_can_have_only_one_direct_chat
Shouldly.ShouldAssertException : Task `CreateChatAsync(ChatType.Direct, bob, [alice])`
should throw
Chatex.Data.Exceptions.UniqueConstraintException
but did notRestore the migration (git restore Source/Chatex.Data/Migrations) and run the test again: it passes.