English
Testing over HTTP
Step 1. The test project
Why. The business tests prove the rules. The API tests prove what only the web layer can get wrong: routes, status codes, the JSON shape (camelCase, enums as strings), Problem Details, the bearer token, the cookie attributes. They run the real application in memory with WebApplicationFactory<Program> from Microsoft.AspNetCore.Mvc.Testing: the whole Program.cs, middleware included, on a test server without network ports, against the PostgreSQL container of topic 6.
Do.
powershell
dotnet new classlib -o Tests/Chatex.Api.Testspowershell
Remove-Item Tests/Chatex.Api.Tests/Class1.cspowershell
dotnet sln add Tests/Chatex.Api.Testspowershell
dotnet add Tests/Chatex.Api.Tests reference Source/Chatex.Apipowershell
dotnet add Tests/Chatex.Api.Tests package Microsoft.AspNetCore.Mvc.TestingRemove the template's <PropertyGroup> and add the framework reference by hand:
xml
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Source\Chatex.Api\Chatex.Api.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" />
</ItemGroup>
</Project><FrameworkReference Include="Microsoft.AspNetCore.App" /> gives the class library the ASP.NET Core types (IWebHostBuilder, HttpContext) that a web project gets from its SDK.
Step 2. Assertions for HTTP responses
Why. HTTP tests check the same things again and again: the status code (with the body in the failure message, otherwise a 400 is a riddle), a JSON body of a given type, a Problem Details body with a given code, a cookie. A few extension methods make each check one line.
Do.
cs
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Chatex.Api.Tests;
internal static class HttpAssertions
{
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web)
{
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) },
};
private static CancellationToken Ct => TestContext.Current.CancellationToken;
public static async Task<T> ShouldHaveAsync<T>(this HttpResponseMessage response, HttpStatusCode status)
where T : class
{
await response.ShouldHaveStatusAsync(status);
var body = await response.Content.ReadFromJsonAsync<T>(Json, Ct);
body.ShouldNotBeNull();
return body;
}
public static async Task ShouldHaveStatusAsync(this HttpResponseMessage response, HttpStatusCode status)
{
if (response.StatusCode != status)
{
var body = await response.Content.ReadAsStringAsync(Ct);
response.StatusCode.ShouldBe(status, $"Body: {body}");
}
}
/// <summary>Checks a problem details response and returns its body.</summary>
public static async Task<JsonElement> ShouldBeProblemAsync(this HttpResponseMessage response, HttpStatusCode status, string? code = null)
{
await response.ShouldHaveStatusAsync(status);
response.Content.Headers.ContentType?.MediaType.ShouldBe("application/problem+json");
var problem = await response.Content.ReadFromJsonAsync<JsonElement>(Ct);
problem.GetProperty("status").GetInt32().ShouldBe((int)status);
if (code is not null)
{
problem.GetProperty("code").GetString().ShouldBe(code);
}
return problem;
}
/// <summary>The value of a cookie the response sets, with its attributes.</summary>
public static string? SetCookie(this HttpResponseMessage response, string name) =>
response.Headers.TryGetValues("Set-Cookie", out var values)
? values.FirstOrDefault(v => v.StartsWith(name + "=", StringComparison.Ordinal))
: null;
public static string CookieValue(string setCookie) => setCookie.Split(';')[0].Split('=', 2)[1];
}Step 3. The base class
Why. Each test class starts the application on a clean database with test settings, and offers a way to create clients — each with its own cookie jar, like a separate browser — and to register a user and get a client that sends that user's token.
Do.
cs
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using Chatex.Api.Contracts;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
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.Api.Tests;
/// <summary>
/// The real Api in memory (TestServer) on a clean database and a temporary upload folder.
/// Clients talk to https://localhost so the Secure refresh cookie round-trips.
/// </summary>
public abstract class ApiTestBase(PostgresFixture fixture) : IAsyncLifetime
{
public const string Password = "Passw0rd!";
protected static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web)
{
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) },
};
private readonly string _storageRoot = Path.Combine(Path.GetTempPath(), "chatex-api-tests", Guid.NewGuid().ToString("N"));
private WebApplicationFactory<Program> _factory = null!;
protected static CancellationToken Ct => TestContext.Current.CancellationToken;
public async ValueTask InitializeAsync()
{
await fixture.ResetAsync();
_factory = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
{
builder
.UseEnvironment("Testing")
.UseSetting("ConnectionStrings:Chatex", fixture.ConnectionString)
.UseSetting("Jwt:Issuer", "chatex-api-tests")
.UseSetting("Jwt:Audience", "chatex-api-tests")
.UseSetting("Jwt:SigningKey", "api-test-signing-key-that-is-long-enough-for-hmac")
.UseSetting("Storage:RootPath", _storageRoot);
});
}
public async ValueTask DisposeAsync()
{
await _factory.DisposeAsync();
if (Directory.Exists(_storageRoot))
{
Directory.Delete(_storageRoot, recursive: true);
}
GC.SuppressFinalize(this);
}
/// <summary>A client with its own cookie jar, like a separate browser.</summary>
protected HttpClient CreateClient() =>
_factory.CreateClient(new WebApplicationFactoryClientOptions { BaseAddress = new Uri("https://localhost") });
/// <summary>Registers <paramref name="userName"/> and returns a client that sends its access token.</summary>
protected async Task<Session> RegisterAsync(string userName)
{
var client = CreateClient();
var response = await client.PostAsJsonAsync("/api/auth/register", RegisterBody(userName), Json, Ct);
var auth = await response.ShouldHaveAsync<AuthResponse>(HttpStatusCode.OK);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", auth.AccessToken);
return new Session(client, auth);
}
protected static object RegisterBody(string userName) => new
{
userName,
email = $"{userName}@example.test",
password = Password,
displayName = $"{userName} display",
};
}
public sealed record Session(HttpClient Client, AuthResponse Auth)
{
public Guid UserId => Auth.User.Id;
}WithWebHostBuilderadjusts the real application for the test: the environmentTesting(soappsettings.Development.jsonis not loaded and Scalar is off), the connection string of the test container, test JWT settings and a temporary upload folder.UseSettingoverrides configuration values.https://localhostas the base address: the refresh cookie isSecure, so it travels only over HTTPS. The test server does not really encrypt anything, but the client's cookie jar follows the rules of the scheme.RegisterAsyncregisters through the real endpoint and sets theAuthorizationheader of the returned client.Sessionkeeps the client and the auth response together.Jsonuses the web defaults (camelCase) and the same enum converter as the API, so tests can deserialize responses into the DTOs of Chatex.Core.
Step 4. The endpoint tests
Do.
cs
using System.Net;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using Chatex.Api.Contracts;
using Chatex.Core.Users;
namespace Chatex.Api.Tests;
public sealed class AuthEndpointsTests(PostgresFixture fixture) : ApiTestBase(fixture)
{
private const string Cookie = "chatex_refresh";
[Fact]
public async Task Register_returns_access_token_and_sets_refresh_cookie()
{
var client = CreateClient();
var response = await client.PostAsJsonAsync("/api/auth/register", RegisterBody("alice"), Json, Ct);
await response.ShouldHaveStatusAsync(HttpStatusCode.OK);
var body = await response.Content.ReadFromJsonAsync<JsonElement>(Ct);
body.GetProperty("accessToken").GetString().ShouldNotBeNullOrEmpty();
body.GetProperty("user").GetProperty("userName").GetString().ShouldBe("alice");
body.TryGetProperty("refreshToken", out _).ShouldBeFalse();
var cookie = response.SetCookie(Cookie).ShouldNotBeNull().ToLowerInvariant();
cookie.ShouldContain("httponly");
cookie.ShouldContain("secure");
cookie.ShouldContain("samesite=strict");
cookie.ShouldContain("path=/api/auth");
}
[Fact]
public async Task Access_token_authenticates_requests()
{
var alice = await RegisterAsync("alice");
var me = await (await alice.Client.GetAsync("/api/me", Ct)).ShouldHaveAsync<MyProfileDto>(HttpStatusCode.OK);
me.Id.ShouldBe(alice.UserId);
me.Email.ShouldBe("[email protected]");
}
[Fact]
public async Task Requests_without_a_token_get_401_problem()
{
var response = await CreateClient().GetAsync("/api/me", Ct);
await response.ShouldBeProblemAsync(HttpStatusCode.Unauthorized);
}
[Fact]
public async Task Login_accepts_user_name_and_rejects_a_wrong_password()
{
await RegisterAsync("alice");
var client = CreateClient();
var ok = await client.PostAsJsonAsync("/api/auth/login", new { login = "alice", password = Password }, Json, Ct);
var wrong = await client.PostAsJsonAsync("/api/auth/login", new { login = "alice", password = "nope12345" }, Json, Ct);
(await ok.ShouldHaveAsync<AuthResponse>(HttpStatusCode.OK)).User.UserName.ShouldBe("alice");
ok.SetCookie(Cookie).ShouldNotBeNull();
await wrong.ShouldBeProblemAsync(HttpStatusCode.Unauthorized, "invalid_credentials");
}
[Fact]
public async Task Refresh_rotates_the_cookie_and_a_reused_token_is_rejected()
{
var client = CreateClient();
var register = await client.PostAsJsonAsync("/api/auth/register", RegisterBody("alice"), Json, Ct);
var firstToken = HttpAssertions.CookieValue(register.SetCookie(Cookie).ShouldNotBeNull());
var refreshed = await client.PostAsync("/api/auth/refresh", null, Ct);
var auth = await refreshed.ShouldHaveAsync<AuthResponse>(HttpStatusCode.OK);
auth.User.UserName.ShouldBe("alice");
HttpAssertions.CookieValue(refreshed.SetCookie(Cookie).ShouldNotBeNull()).ShouldNotBe(firstToken);
var replay = new HttpRequestMessage(HttpMethod.Post, "/api/auth/refresh");
replay.Headers.Add("Cookie", $"{Cookie}={firstToken}");
var reused = await CreateClient().SendAsync(replay, Ct);
await reused.ShouldBeProblemAsync(HttpStatusCode.Unauthorized, "invalid_refresh_token");
// Reuse signs the user out everywhere, so the newest cookie stops working too.
var afterReuse = await client.PostAsync("/api/auth/refresh", null, Ct);
await afterReuse.ShouldBeProblemAsync(HttpStatusCode.Unauthorized, "invalid_refresh_token");
}
[Fact]
public async Task Refresh_without_a_cookie_is_401()
{
var response = await CreateClient().PostAsync("/api/auth/refresh", null, Ct);
await response.ShouldBeProblemAsync(HttpStatusCode.Unauthorized, "invalid_refresh_token");
}
[Fact]
public async Task Logout_clears_the_cookie_and_ends_the_session()
{
var client = CreateClient();
var register = await client.PostAsJsonAsync("/api/auth/register", RegisterBody("alice"), Json, Ct);
var token = HttpAssertions.CookieValue(register.SetCookie(Cookie).ShouldNotBeNull());
var logout = await client.PostAsync("/api/auth/logout", null, Ct);
await logout.ShouldHaveStatusAsync(HttpStatusCode.NoContent);
logout.SetCookie(Cookie).ShouldNotBeNull().ShouldContain("expires=Thu, 01 Jan 1970", Case.Insensitive);
var replay = new HttpRequestMessage(HttpMethod.Post, "/api/auth/refresh");
replay.Headers.Add("Cookie", $"{Cookie}={token}");
await (await CreateClient().SendAsync(replay, Ct)).ShouldBeProblemAsync(HttpStatusCode.Unauthorized);
}
[Fact]
public async Task Duplicate_user_name_is_409()
{
await RegisterAsync("alice");
var response = await CreateClient().PostAsJsonAsync("/api/auth/register", RegisterBody("alice"), Json, Ct);
await response.ShouldBeProblemAsync(HttpStatusCode.Conflict, "user_name_taken");
}
[Fact]
public async Task Invalid_fields_are_400_with_per_field_errors()
{
var body = new { userName = "a", email = "not-an-email", password = Password, displayName = "A" };
var response = await CreateClient().PostAsJsonAsync("/api/auth/register", body, Json, Ct);
var problem = await response.ShouldBeProblemAsync(HttpStatusCode.BadRequest, "validation_failed");
var errors = problem.GetProperty("errors");
errors.TryGetProperty("userName", out _).ShouldBeTrue();
errors.TryGetProperty("email", out _).ShouldBeTrue();
}
[Fact]
public async Task Malformed_json_is_400_problem()
{
var content = new StringContent("{ not json", Encoding.UTF8, "application/json");
var response = await CreateClient().PostAsync("/api/auth/login", content, Ct);
await response.ShouldBeProblemAsync(HttpStatusCode.BadRequest);
}
}The auth tests check the contract with the browser: the token is in the body and the refresh token is not; the cookie has all four attributes; a request without a token gets a 401 Problem Details; refresh rotates the cookie and a reused cookie signs the user out everywhere; logout expires the cookie; duplicates are 409, invalid fields 400 with errors per field, malformed JSON a 400 Problem Details.
cs
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Chatex.Api.Contracts;
using Chatex.Core.Chats;
using Chatex.Core.Common;
using Chatex.Core.Messages;
using Chatex.Data.Entities;
namespace Chatex.Api.Tests;
public sealed class ChatAndMessageEndpointsTests(PostgresFixture fixture) : ApiTestBase(fixture)
{
[Fact]
public async Task Creating_a_group_returns_201_with_location_and_camel_case_enums()
{
var alice = await RegisterAsync("alice");
var bob = await RegisterAsync("bob");
var response = await alice.Client.PostAsJsonAsync(
"/api/chats", new { type = "group", title = "Team", memberIds = new[] { bob.UserId } }, Json, Ct);
await response.ShouldHaveStatusAsync(HttpStatusCode.Created);
var raw = await response.Content.ReadFromJsonAsync<JsonElement>(Ct);
raw.GetProperty("type").GetString().ShouldBe("group");
raw.GetProperty("myRole").GetString().ShouldBe("owner");
var chat = raw.Deserialize<ChatDto>(Json).ShouldNotBeNull();
chat.MemberCount.ShouldBe(2);
response.Headers.Location.ShouldBe(new Uri($"/api/chats/{chat.Id}", UriKind.Relative));
var fetched = await (await bob.Client.GetAsync($"/api/chats/{chat.Id}", Ct)).ShouldHaveAsync<ChatDto>(HttpStatusCode.OK);
fetched.MyRole.ShouldBe(ChatMemberRole.Member);
}
[Fact]
public async Task Messages_can_be_sent_read_edited_and_deleted()
{
var alice = await RegisterAsync("alice");
var bob = await RegisterAsync("bob");
var chat = await CreateGroupAsync(alice, bob.UserId);
var sent = await (await bob.Client.PostAsJsonAsync($"/api/chats/{chat.Id}/messages", new { body = "hi all" }, Json, Ct))
.ShouldHaveAsync<MessageDto>(HttpStatusCode.Created);
await SendAsync(alice, chat.Id, "hello bob");
var page = await (await alice.Client.GetAsync($"/api/chats/{chat.Id}/messages?limit=1", Ct))
.ShouldHaveAsync<PageDto<MessageDto>>(HttpStatusCode.OK);
page.Items.Single().Body.ShouldBe("hello bob");
page.NextCursor.ShouldNotBeNull();
var older = await (await alice.Client.GetAsync($"/api/chats/{chat.Id}/messages?before={page.NextCursor}", Ct))
.ShouldHaveAsync<PageDto<MessageDto>>(HttpStatusCode.OK);
older.Items.Single().Id.ShouldBe(sent.Id);
older.NextCursor.ShouldBeNull();
var edited = await (await bob.Client.PutAsJsonAsync($"/api/messages/{sent.Id}", new { body = "hi everyone" }, Json, Ct))
.ShouldHaveAsync<MessageDto>(HttpStatusCode.OK);
edited.Body.ShouldBe("hi everyone");
edited.EditedAt.ShouldNotBeNull();
var notSender = await alice.Client.PutAsJsonAsync($"/api/messages/{sent.Id}", new { body = "hacked" }, Json, Ct);
await notSender.ShouldBeProblemAsync(HttpStatusCode.Forbidden, "not_sender");
await (await bob.Client.DeleteAsync($"/api/messages/{sent.Id}", Ct)).ShouldHaveStatusAsync(HttpStatusCode.NoContent);
var after = await (await alice.Client.GetAsync($"/api/chats/{chat.Id}/messages", Ct))
.ShouldHaveAsync<PageDto<MessageDto>>(HttpStatusCode.OK);
after.Items.Single(m => m.Id == sent.Id).IsDeleted.ShouldBeTrue();
}
[Fact]
public async Task Outsiders_cannot_read_a_private_group()
{
var alice = await RegisterAsync("alice");
var eve = await RegisterAsync("eve");
var chat = await CreateGroupAsync(alice);
var response = await eve.Client.GetAsync($"/api/chats/{chat.Id}/messages", Ct);
await response.ShouldBeProblemAsync(HttpStatusCode.NotFound, "chat_not_found");
}
[Fact]
public async Task Unknown_chat_is_404_problem()
{
var alice = await RegisterAsync("alice");
var response = await alice.Client.GetAsync($"/api/chats/{Guid.NewGuid()}", Ct);
await response.ShouldBeProblemAsync(HttpStatusCode.NotFound, "chat_not_found");
}
[Fact]
public async Task Public_channels_can_be_found_and_joined_but_subscribers_cannot_post()
{
var alice = await RegisterAsync("alice");
var bob = await RegisterAsync("bob");
var created = await alice.Client.PostAsJsonAsync(
"/api/chats", new { type = "channel", title = "News", publicHandle = "news_room" }, Json, Ct);
var channel = await created.ShouldHaveAsync<ChatDto>(HttpStatusCode.Created);
var found = await (await bob.Client.GetAsync("/api/chats/search?query=news", Ct))
.ShouldHaveAsync<ChatSummaryDto[]>(HttpStatusCode.OK);
found.ShouldContain(c => c.Id == channel.Id);
var joined = await (await bob.Client.PostAsync($"/api/chats/{channel.Id}/join", null, Ct))
.ShouldHaveAsync<ChatDto>(HttpStatusCode.OK);
joined.MyRole.ShouldBe(ChatMemberRole.Subscriber);
var post = await bob.Client.PostAsJsonAsync($"/api/chats/{channel.Id}/messages", new { body = "me too" }, Json, Ct);
await post.ShouldBeProblemAsync(HttpStatusCode.Forbidden, "cannot_post");
}
[Fact]
public async Task Direct_chat_members_roles_and_read_state()
{
var alice = await RegisterAsync("alice");
var bob = await RegisterAsync("bob");
var carol = await RegisterAsync("carol");
var direct = await (await alice.Client.PostAsJsonAsync("/api/chats/direct", new OpenDirectRequest(bob.UserId), Json, Ct))
.ShouldHaveAsync<ChatDto>(HttpStatusCode.OK);
direct.Type.ShouldBe(ChatType.Direct);
direct.Peer.ShouldNotBeNull().Id.ShouldBe(bob.UserId);
var group = await CreateGroupAsync(alice);
var added = await (await alice.Client.PostAsJsonAsync(
$"/api/chats/{group.Id}/members", new AddMembersRequest([bob.UserId, carol.UserId]), Json, Ct))
.ShouldHaveAsync<AddMembersResponse>(HttpStatusCode.OK);
added.Added.ShouldBe(2);
await (await alice.Client.PutAsJsonAsync(
$"/api/chats/{group.Id}/members/{bob.UserId}/role", new { role = "admin" }, Json, Ct))
.ShouldHaveStatusAsync(HttpStatusCode.NoContent);
await (await bob.Client.DeleteAsync($"/api/chats/{group.Id}/members/{carol.UserId}", Ct))
.ShouldHaveStatusAsync(HttpStatusCode.NoContent);
var members = await (await alice.Client.GetAsync($"/api/chats/{group.Id}/members", Ct))
.ShouldHaveAsync<PageDto<ChatMemberDto>>(HttpStatusCode.OK);
members.Items.Select(m => (m.User.Id, m.Role)).ShouldBe(
[(alice.UserId, ChatMemberRole.Owner), (bob.UserId, ChatMemberRole.Admin)], ignoreOrder: true);
var message = await SendAsync(alice, group.Id, "unread for bob");
var unread = await BobsChatAsync(bob, group.Id);
unread.UnreadCount.ShouldBe(1);
await (await bob.Client.PostAsJsonAsync($"/api/chats/{group.Id}/read", new MarkReadRequest(message.Id), Json, Ct))
.ShouldHaveStatusAsync(HttpStatusCode.NoContent);
await (await bob.Client.PutAsJsonAsync($"/api/chats/{group.Id}/mute", new SetMutedRequest(true), Json, Ct))
.ShouldHaveStatusAsync(HttpStatusCode.NoContent);
var read = await BobsChatAsync(bob, group.Id);
read.UnreadCount.ShouldBe(0);
read.IsMuted.ShouldBeTrue();
}
private static async Task<ChatListItemDto> BobsChatAsync(Session bob, Guid chatId)
{
var page = await (await bob.Client.GetAsync("/api/chats", Ct)).ShouldHaveAsync<PageDto<ChatListItemDto>>(HttpStatusCode.OK);
return page.Items.Single(c => c.Id == chatId);
}
private static async Task<ChatDto> CreateGroupAsync(Session owner, params Guid[] memberIds)
{
var response = await owner.Client.PostAsJsonAsync(
"/api/chats", new { type = "group", title = "Team", memberIds }, Json, Ct);
return await response.ShouldHaveAsync<ChatDto>(HttpStatusCode.Created);
}
private static async Task<MessageDto> SendAsync(Session sender, Guid chatId, string body)
{
var response = await sender.Client.PostAsJsonAsync($"/api/chats/{chatId}/messages", new { body }, Json, Ct);
return await response.ShouldHaveAsync<MessageDto>(HttpStatusCode.Created);
}
}The chat tests go through the most important flows over HTTP: creating a group (201, Location, enums as "group" and "owner"), sending, paging with the opaque cursor, editing, deleting; a private group is 404 for outsiders; a public channel is found, joined, and refuses posts from subscribers; direct chats, members, roles, unread counters, read positions and mute.
Check
powershell
dotnet test --solution Chatex.slnx76 tests pass: 19 data, 41 business and 16 API tests. The three test projects run in parallel, each with its own PostgreSQL container.