English
Testing the business layer
Step 1. The test project
Why. The business layer gets its own test project. Its tests call the services through the real dependency injection graph — AddCore with the real data layer on the PostgreSQL container of topic 6 — so a test checks the rule, the query and the transaction together. Only three things are replaced: the clock, the file storage (topic 9) and the notifier (topic 10).
Do.
powershell
dotnet new classlib -o Tests/Chatex.Core.Testspowershell
Remove-Item Tests/Chatex.Core.Tests/Class1.cspowershell
dotnet sln add Tests/Chatex.Core.Testspowershell
dotnet add Tests/Chatex.Core.Tests reference Source/Chatex.Corepowershell
dotnet add Tests/Chatex.Core.Tests package Microsoft.Extensions.Configurationpowershell
dotnet add Tests/Chatex.Core.Tests package Microsoft.Extensions.TimeProvider.TestingRemove the <PropertyGroup> that the template wrote. The name ends with .Tests, so Tests/Directory.Build.props of topic 6 makes it a test project with xUnit, Shouldly and Chatex.Testing:
xml
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\..\Source\Chatex.Core\Chatex.Core.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" />
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" />
</ItemGroup>
</Project>Microsoft.Extensions.Configurationbuilds a configuration from an in-memory dictionary — the settingsAddCorereads.Microsoft.Extensions.TimeProvider.TestingcontainsFakeTimeProvider: aTimeProviderwhose time stands still until the test moves it withAdvance(TimeSpan). A test of "a refresh token expires after 30 days" advances the clock by 31 days in one line.
Step 2. The base class
Why. Like DbTestBase in topic 6, a base class does the repetitive work: it configures the services and offers short helpers. Two ideas shape it:
- One scope per service call.
Auth(s => s.LoginAsync(...))creates a new scope, resolves the service, calls it and disposes the scope — exactly like one HTTP request. Nothing tracked by the context of one call can make the next call pass by accident. - Assertions that read like the rules.
result.ShouldSucceed()returns the value or fails with the error in the message;result.ShouldFail(ErrorKind.Conflict, "user_name_taken")checks the kind and the code.
Do.
cs
using Chatex.Core.Auth;
using Chatex.Core.Common;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Time.Testing;
// Tests share one database that is wiped before each test; xunit.runner.json turns off parallel runs.
[assembly: AssemblyFixture(typeof(PostgresFixture))]
namespace Chatex.Core.Tests;
public abstract class BusinessTestBase(PostgresFixture fixture) : DatabaseTest(fixture)
{
public const string Password = "Passw0rd!";
public const string Issuer = "chatex-tests";
public const string SigningKey = "test-signing-key-that-is-long-enough-for-hmac";
protected FakeTimeProvider Time { get; } = new(DateTimeOffset.UtcNow);
protected override void ConfigureServices(IServiceCollection services, string connectionString)
{
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?>
{
["ConnectionStrings:Chatex"] = connectionString,
["Storage:RootPath"] = StorageRoot,
["Jwt:Issuer"] = Issuer,
["Jwt:Audience"] = Issuer,
["Jwt:SigningKey"] = SigningKey,
})
.Build();
services.AddSingleton<TimeProvider>(Time);
services.AddCore(configuration);
}
protected Task<T> Auth<T>(Func<IAuthService, Task<T>> call) => Use(call);
/// <summary>Registers <paramref name="userName"/> and returns the signed-in session.</summary>
protected async Task<AuthResult> RegisterAsync(string userName)
{
var result = await Auth(s => s.RegisterAsync(
new RegisterCommand(userName, $"{userName}@example.test", Password, $"{userName} display"), ClientInfo.Unknown, Ct));
return result.ShouldSucceed();
}
protected async Task<Guid> RegisterUserAsync(string userName) => (await RegisterAsync(userName)).User.Id;
private async Task<T> Use<TService, T>(Func<TService, Task<T>> call) where TService : notnull
{
await using var scope = NewScope();
return await call(Get<TService>(scope));
}
}
internal static class ResultAssertions
{
public static T ShouldSucceed<T>(this Result<T> result)
{
result.IsSuccess.ShouldBeTrue($"Expected success but got {result.Error}");
return result.Value;
}
public static void ShouldSucceed(this Result result) =>
result.IsSuccess.ShouldBeTrue($"Expected success but got {result.Error}");
public static Error ShouldFail<T>(this Result<T> result, ErrorKind kind, string code)
{
result.IsSuccess.ShouldBeFalse("Expected a failure but the operation succeeded.");
result.Error.Kind.ShouldBe(kind);
result.Error.Code.ShouldBe(code);
return result.Error;
}
public static Error ShouldFail(this Result result, ErrorKind kind, string code)
{
result.IsSuccess.ShouldBeFalse("Expected a failure but the operation succeeded.");
result.Error.Kind.ShouldBe(kind);
result.Error.Code.ShouldBe(code);
return result.Error;
}
}[assembly: AssemblyFixture(typeof(PostgresFixture))]gives this test project its own PostgreSQL container, like the data tests.ConfigureServicesbuilds the configuration the API will read fromappsettings— connection string, storage folder, JWT settings — and registers the fake clock beforeAddCore.AddDataregisters the real clock withTryAddSingleton(topic 5), which does nothing when aTimeProvideris already there.Auth<T>and the privateUse<TService, T>implement "one scope per call".Useis generic over the service type; each feature gets a one-line helper (Profiles,Chats, … in the next topics).RegisterAsyncregisters a user with a fixed password and returns the session;RegisterUserAsyncreturns only the id. Most tests start with them.ResultAssertionsare extension methods for bothResultandResult<T>. They live in the same file,internalto the test project.
Step 3. The tests of the auth service
Do.
cs
using System.Text;
using Chatex.Core.Auth;
using Chatex.Core.Common;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
namespace Chatex.Core.Tests;
public sealed class AuthServiceTests(PostgresFixture fixture) : BusinessTestBase(fixture)
{
[Fact]
public async Task Register_signs_the_user_in_and_creates_the_profile()
{
var result = await Auth(s => s.RegisterAsync(
new RegisterCommand("Alice_1", "[email protected]", Password, " Alice "), ClientInfo.Unknown, Ct));
var session = result.ShouldSucceed();
session.AccessToken.ShouldNotBeNullOrEmpty();
session.RefreshToken.ShouldNotBeNullOrEmpty();
session.User.UserName.ShouldBe("alice_1");
session.User.DisplayName.ShouldBe("Alice");
session.RefreshTokenExpiresAt.ShouldBe(Time.GetUtcNow() + TimeSpan.FromDays(30));
}
[Fact]
public async Task Register_rejects_a_taken_user_name_in_any_case()
{
await RegisterAsync("alice");
var result = await Auth(s => s.RegisterAsync(
new RegisterCommand("ALICE", "[email protected]", Password, "Other"), ClientInfo.Unknown, Ct));
result.ShouldFail(ErrorKind.Conflict, "user_name_taken");
}
[Fact]
public async Task Register_rejects_a_weak_password_and_an_invalid_user_name()
{
var weak = await Auth(s => s.RegisterAsync(
new RegisterCommand("alice", "[email protected]", "short", "Alice"), ClientInfo.Unknown, Ct));
var badName = await Auth(s => s.RegisterAsync(
new RegisterCommand("1alice!", "[email protected]", Password, "Alice"), ClientInfo.Unknown, Ct));
weak.ShouldFail(ErrorKind.Validation, "validation_failed").Details.ShouldNotBeNull().ShouldContainKey("password");
badName.ShouldFail(ErrorKind.Validation, "validation_failed").Details.ShouldNotBeNull().ShouldContainKey("userName");
}
[Fact]
public async Task Login_works_with_user_name_or_email()
{
var alice = await RegisterUserAsync("alice");
var byName = await Auth(s => s.LoginAsync(new LoginCommand("Alice", Password), ClientInfo.Unknown, Ct));
var byEmail = await Auth(s => s.LoginAsync(new LoginCommand("[email protected]", Password), ClientInfo.Unknown, Ct));
byName.ShouldSucceed().User.Id.ShouldBe(alice);
byEmail.ShouldSucceed().User.Id.ShouldBe(alice);
}
[Fact]
public async Task Login_locks_the_account_after_five_wrong_passwords()
{
await RegisterAsync("alice");
for (var attempt = 1; attempt <= 4; attempt++)
{
(await Auth(s => s.LoginAsync(new LoginCommand("alice", "Wrong1234"), ClientInfo.Unknown, Ct)))
.ShouldFail(ErrorKind.Unauthorized, "invalid_credentials");
}
(await Auth(s => s.LoginAsync(new LoginCommand("alice", "Wrong1234"), ClientInfo.Unknown, Ct)))
.ShouldFail(ErrorKind.Unauthorized, "locked_out");
(await Auth(s => s.LoginAsync(new LoginCommand("alice", Password), ClientInfo.Unknown, Ct)))
.ShouldFail(ErrorKind.Unauthorized, "locked_out");
}
[Fact]
public async Task Login_does_not_reveal_whether_the_user_exists()
{
var result = await Auth(s => s.LoginAsync(new LoginCommand("nobody", Password), ClientInfo.Unknown, Ct));
result.ShouldFail(ErrorKind.Unauthorized, "invalid_credentials");
}
[Fact]
public async Task Refresh_issues_a_new_pair_and_retires_the_old_token()
{
var first = await RegisterAsync("alice");
var second = (await Auth(s => s.RefreshAsync(new RefreshCommand(first.RefreshToken), ClientInfo.Unknown, Ct))).ShouldSucceed();
var third = await Auth(s => s.RefreshAsync(new RefreshCommand(second.RefreshToken), ClientInfo.Unknown, Ct));
second.RefreshToken.ShouldNotBe(first.RefreshToken);
second.User.Id.ShouldBe(first.User.Id);
third.ShouldSucceed();
}
[Fact]
public async Task Reusing_a_refresh_token_signs_the_user_out_everywhere()
{
var first = await RegisterAsync("alice");
var second = (await Auth(s => s.RefreshAsync(new RefreshCommand(first.RefreshToken), ClientInfo.Unknown, Ct))).ShouldSucceed();
var replay = await Auth(s => s.RefreshAsync(new RefreshCommand(first.RefreshToken), ClientInfo.Unknown, Ct));
var afterReplay = await Auth(s => s.RefreshAsync(new RefreshCommand(second.RefreshToken), ClientInfo.Unknown, Ct));
replay.ShouldFail(ErrorKind.Unauthorized, "invalid_refresh_token");
afterReplay.ShouldFail(ErrorKind.Unauthorized, "invalid_refresh_token");
}
[Fact]
public async Task Refresh_fails_once_the_token_expired()
{
var session = await RegisterAsync("alice");
Time.Advance(TimeSpan.FromDays(31));
var result = await Auth(s => s.RefreshAsync(new RefreshCommand(session.RefreshToken), ClientInfo.Unknown, Ct));
result.ShouldFail(ErrorKind.Unauthorized, "invalid_refresh_token");
}
[Fact]
public async Task Stale_refresh_tokens_are_deleted_only_after_a_full_lifetime()
{
var first = await RegisterAsync("alice");
var second = (await Auth(s => s.RefreshAsync(new RefreshCommand(first.RefreshToken), ClientInfo.Unknown, Ct))).ShouldSucceed();
// The retired token is kept, so replaying it is still caught as theft.
(await Auth(s => s.DeleteStaleRefreshTokensAsync(Ct))).ShouldBe(0);
Time.Advance(TimeSpan.FromDays(61));
(await Auth(s => s.DeleteStaleRefreshTokensAsync(Ct))).ShouldBe(2);
var result = await Auth(s => s.RefreshAsync(new RefreshCommand(second.RefreshToken), ClientInfo.Unknown, Ct));
result.ShouldFail(ErrorKind.Unauthorized, "invalid_refresh_token");
}
[Fact]
public async Task Logout_ends_the_session()
{
var session = await RegisterAsync("alice");
(await Auth(s => s.LogoutAsync(new RefreshCommand(session.RefreshToken), Ct))).ShouldSucceed();
var result = await Auth(s => s.RefreshAsync(new RefreshCommand(session.RefreshToken), ClientInfo.Unknown, Ct));
result.ShouldFail(ErrorKind.Unauthorized, "invalid_refresh_token");
}
[Fact]
public async Task Access_token_is_signed_and_identifies_the_user()
{
var session = await RegisterAsync("alice");
var validation = await new JsonWebTokenHandler().ValidateTokenAsync(session.AccessToken, new TokenValidationParameters
{
ValidIssuer = Issuer,
ValidAudience = Issuer,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SigningKey)),
});
validation.IsValid.ShouldBeTrue(validation.Exception?.Message);
validation.Claims[JwtRegisteredClaimNames.Sub].ShouldBe(session.User.Id.ToString());
validation.Claims[JwtRegisteredClaimNames.UniqueName].ShouldBe("alice");
}
}What the twelve tests prove:
- Registration lower-cases the user name, trims the display name, signs the user in, and the refresh token expires exactly 30 days after the fake "now". A taken name is rejected in any letter case; a weak password and an invalid name are reported under their fields.
- Sign-in works with the name (in another case) and with the email. Five wrong passwords lock the account: four answers
invalid_credentials, the fifthlocked_out— and then even the right password is refused. An unknown user gets exactly the same error as a wrong password. - Refresh returns a new refresh token that works once more. Reusing the first token fails, and afterwards even the newest token is dead: the user was signed out everywhere.
- Expiry and cleanup use the fake clock: 31 days later the token is refused; the cleanup keeps the retired token at first (so theft is still detected) and deletes both tokens of the session after 61 days.
- The access token is validated with the JWT library, independently of the service: correct issuer, audience and signature,
subis the user id andunique_namethe user name.
Check
powershell
dotnet test --solution Chatex.slnxBoth test projects run in parallel, each with its own container. The summary shows 31 tests: 19 data tests and 12 business tests, all passing.
Then make one test fail on purpose: in AuthService.RefreshAsync, comment out the line await refreshTokens.RevokeAllForUserAsync(...) inside the theft branch and run
powershell
dotnet test --project Tests/Chatex.Core.Tests --filter-method "*Reusing*"The test Reusing_a_refresh_token_signs_the_user_out_everywhere fails: the second token still works. Restore the line.