The walk
xunit: a Fact is one case, a Theory is a table
A [Fact] is a test with no parameters. A [Theory] takes rows of
[InlineData] and runs once per row, which is how a rule with tiers is
covered without six copies of the same test. Assertions are the static
Assert class; the test's name is a sentence with underscores, so a
failing run reads like a report. The domain tests need no host and no
file: BidRules is a static class of pure functions, so the test hands it
values and checks the answer.
[Theory]
[InlineData(3500, 100)]
[InlineData(4999, 100)]
[InlineData(5000, 250)]
[InlineData(19999, 250)]
[InlineData(20000, 500)]
[InlineData(77000, 500)]
public void Increments_are_tiered(int currentBid, int expected)
{
Assert.Equal(expected, BidRules.Increment(currentBid));
}
[Fact]
public void Min_next_bid_adds_the_increment_or_is_the_opening_ask()
{
Assert.Equal(23_300, BidRules.MinNextBid(TestData.Vehicle(currentBid: 22_800)));
Assert.Equal(14_500, BidRules.MinNextBid(TestData.Vehicle(currentBid: null)));
}
Live from api/TheYard.Tests/BidRulesTests.cs, region tiers, read from this build at 99df7a8.
Builders instead of fixtures files
Every test that needs a vehicle asks TestData.Vehicle(...) for one and
overrides only the fields it cares about. A test reads as its intent
(currentBid: null, bodyStyle: "van") instead of a forty-line object,
and a new required field on Vehicle is added in one place. The clock
helper does the same for time: an AuctionClock anchored to a chosen
midnight, so a test never depends on when it runs.
public static AuctionClock ClockAt(DateTimeOffset now) =>
new(
now.ToUnixTimeMilliseconds(),
new DateTimeOffset(now.Year, now.Month, now.Day, 0, 0, 0, now.Offset).ToUnixTimeMilliseconds());
public static Vehicle Vehicle(
string id = "test-id",
string make = "Ford",
string bodyStyle = "SUV",
IReadOnlyList<string>? images = null,
int? currentBid = 22800) => new()
{
Id = id,
Vin = "TRD7L1KS0HNB5X3K3",
Year = 2023,
Make = make,
Model = "Bronco",
Trim = "Big Bend",
BodyStyle = bodyStyle,
ExteriorColor = "Burgundy",
InteriorColor = "Beige",
Engine = "2.7L EcoBoost V6",
Transmission = "automatic",
Drivetrain = "4WD",
OdometerKm = 47731,
FuelType = "gasoline",
ConditionGrade = 3.8,
ConditionReport = "Average condition.",
DamageNotes = ["Scratch on liftgate"],
TitleStatus = "clean",
Province = "Ontario",
City = "Toronto",
AuctionStart = "2026-04-05T14:00:00",
StartingBid = 14500,
ReservePrice = 25000,
BuyNowPrice = null,
Images = images ?? ["https://placehold.co/800x600"],
SellingDealership = "King City Auto",
Lot = "A-0043",
CurrentBid = currentBid,
BidCount = 16,
};
Live from api/TheYard.Tests/TestData.cs, region builders, read from this build at 99df7a8.
Fakes at the ports
InventoryService takes an IVehicleSource and an IPhotoManifestSource.
In production those are the JSON file adapters; in a test they are two
tiny classes declared in the test file with the file modifier, which
keeps them invisible to every other file. That is the onion architecture
paying for itself: the service is tested with no filesystem, and the
LoadCalls counter proves the dataset is read once.
file sealed class FakeVehicles(params Vehicle[] vehicles) : IVehicleSource
{
public int LoadCalls { get; private set; }
public Task<IReadOnlyList<Vehicle>> LoadAsync(CancellationToken cancellation)
{
LoadCalls++;
return Task.FromResult<IReadOnlyList<Vehicle>>(vehicles);
}
}
file sealed class FakeManifest(params PhotoEntry[] photos) : IPhotoManifestSource
{
public Task<IReadOnlyList<PhotoEntry>> LoadAsync(CancellationToken cancellation) => Task.FromResult<IReadOnlyList<PhotoEntry>>(photos);
}
file sealed class FlakyVehicles(params Vehicle[] vehicles) : IVehicleSource
{
public int LoadCalls { get; private set; }
public Task<IReadOnlyList<Vehicle>> LoadAsync(CancellationToken cancellation)
{
LoadCalls++;
return LoadCalls == 1
? Task.FromException<IReadOnlyList<Vehicle>>(new IOException("the store is not answering"))
: Task.FromResult<IReadOnlyList<Vehicle>>(vehicles);
}
}
file sealed class CountingStore(IReadOnlyList<Vehicle> vehicles, int filled, CatalogueFillPace pace) : IVehicleCatalogue
{
private readonly MemoryCatalogue _inner = new(vehicles);
public int Filled { get; private set; } = filled;
public int Pages { get; private set; }
public int Counts { get; private set; }
public int Written { get; private set; }
public int AskedToExclude { get; private set; }
public int Target => vehicles.Count;
public CatalogueFillPace Pace => pace;
public Task<int> FilledAsync(CancellationToken cancellation) => Task.FromResult(Filled);
public Task FillAsync(IReadOnlyList<CatalogueEntry> batch, CancellationToken cancellation)
{
Written += batch.Count;
Filled = Math.Max(Filled, batch.Max(entry => entry.Seq) + 1);
return Task.CompletedTask;
}
public Task<SegmentCounts> CountAsync(CatalogueFilter filter, CancellationToken cancellation)
{
Counts++;
AskedToExclude += filter.Exclude.Count > 0 ? 1 : 0;
return _inner.CountAsync(filter, CancellationToken.None);
}
public Task<IReadOnlyList<CatalogueEntry>> PageAsync(CatalogueFilter filter, CatalogueOrder order, int skip, int take, CancellationToken cancellation)
{
Pages++;
AskedToExclude += filter.Exclude.Count > 0 ? 1 : 0;
return _inner.PageAsync(filter, order, skip, take, CancellationToken.None);
}
public Task<IReadOnlyList<CatalogueEntry>> FindAsync(IReadOnlyCollection<string> ids, CancellationToken cancellation) => _inner.FindAsync(ids, CancellationToken.None);
public Task<InventoryFacets> FacetsAsync(CancellationToken cancellation) => _inner.FacetsAsync(CancellationToken.None);
}
Live from api/TheYard.Tests/StockTests.cs, region fakes, read from this build at 99df7a8.
Integration tests boot the real host in memory
WebApplicationFactory<Program> starts Program.cs inside the test process
with an in-memory server, so _client.GetAsync("/api/vehicles") runs the
real routing, binding, services and serializer with no port and no
process. IClassFixture shares one host across a class, which is why the
bid lifecycle has a class of its own: its bids would otherwise leak into
the read-only tests. The public partial class Program; line at the end
of Program.cs exists for this factory (ADR: Program.cs, explained).
[Collection(SharedBidStore.Name)]
public class BidFlowIntegrationTests(WebApplicationFactory<Program> factory)
: IClassFixture<WebApplicationFactory<Program>>, IAsyncLifetime
{
private HttpClient _client = null!;
public async Task InitializeAsync() => _client = await Buyers.SignedIn(factory);
public Task DisposeAsync()
{
_client.Dispose();
return Task.CompletedTask;
}
private async Task<JsonDocument> GetAsync(string url) =>
JsonDocument.Parse(await _client.GetStringAsync(url));
[Fact]
public async Task Bid_lifecycle_place_verify_buy_now_and_reset()
{
using var live = await GetAsync("/api/vehicles?status=live&sort=most-bids&limit=50");
string id = "";
int min = 0, bidCount = 0;
foreach (var candidate in live.RootElement.GetProperty("vehicles").EnumerateArray().Skip(5).Where(vehicle => !vehicle.GetProperty("sold").GetBoolean()))
{
id = candidate.GetProperty("id").GetString()!;
using var fresh = await GetAsync($"/api/vehicles/{id}");
if (fresh.RootElement.GetProperty("sold").GetBoolean())
{
continue;
}
min = fresh.RootElement.GetProperty("min_next_bid").GetInt32();
bidCount = fresh.RootElement.GetProperty("bid_count").GetInt32();
break;
}
var placed = await _client.PostAsJsonAsync($"/api/vehicles/{id}/bids",
new { amount = min });
Assert.Equal(HttpStatusCode.OK, placed.StatusCode);
using var placedJson = JsonDocument.Parse(await placed.Content.ReadAsStringAsync());
Assert.Equal("accepted", placedJson.RootElement.GetProperty("kind").GetString());
Assert.Equal(bidCount + 1,
placedJson.RootElement.GetProperty("bid").GetProperty("bid_count").GetInt32());
using var after = await GetAsync($"/api/vehicles/{id}");
Assert.Equal(min, after.RootElement.GetProperty("current_bid").GetInt32());
Assert.True(after.RootElement.GetProperty("min_next_bid").GetInt32() > min);
var tooLow = await _client.PostAsJsonAsync($"/api/vehicles/{id}/bids",
new { amount = min });
Assert.Equal(HttpStatusCode.BadRequest, tooLow.StatusCode);
Live from api/TheYard.Tests/BidFlowIntegrationTests.cs, region lifecycle, read from this build at 99df7a8.
Two habits in that test are worth copying. The anchor is captured once and
sent with every request, so the whole test sees one clock. And the target
vehicle is chosen by sorting live auctions by most bids: its window ends
hours or days out, so it cannot flip to ended halfway through the test.
Vitest: the browser's logic without a browser
src/lib is plain TypeScript, so its tests run in Node in milliseconds.
The interesting ones are the cache tests: vi.stubGlobal('fetch', ...)
replaces the network with a counter, and fake timers let a five-minute
TTL expire in a line. Vitest is configured in vite.config.ts (ADR: The
React configuration, explained), and the include pattern keeps it to
src/**/*.test.ts.
describe('fetchVehicles caching', () => {
const okResponse = () =>
({
ok: true,
json: async () => ({ total: 1, vehicles: [{ id: 'v1' }] }),
}) as unknown as Response;
beforeEach(() => {
clearVehicleCache();
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-08-16T12:00:00'));
});
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
});
it('serves a repeated query from the cache', async () => {
const fetchMock = vi.fn().mockImplementation(async () => okResponse());
vi.stubGlobal('fetch', fetchMock);
await fetchVehicles();
await fetchVehicles();
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('caches per query-parameter combination, including sort', async () => {
const fetchMock = vi.fn().mockImplementation(async () => okResponse());
vi.stubGlobal('fetch', fetchMock);
await fetchVehicles({ ...EMPTY_FILTERS, make: 'Ford' });
await fetchVehicles({ ...EMPTY_FILTERS, make: 'Ford' }, { sort: 'price-asc' });
await fetchVehicles({ ...EMPTY_FILTERS, make: 'Ford' });
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('expires entries after the TTL', async () => {
const fetchMock = vi.fn().mockImplementation(async () => okResponse());
vi.stubGlobal('fetch', fetchMock);
await fetchVehicles();
vi.advanceTimersByTime(5 * 60 * 1000 + 1);
await fetchVehicles();
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('asks the API with the query string and never with the cache key', async () => {
const fetchMock = vi.fn().mockImplementation(async () => okResponse());
vi.stubGlobal('fetch', fetchMock);
await fetchVehicles();
await fetchVehicles({ ...EMPTY_FILTERS, make: 'Ford' }, { sort: 'price-asc', offset: 100 });
expect(fetchMock.mock.calls[0][0]).toBe('/api/vehicles');
expect(fetchMock.mock.calls[1][0]).toBe('/api/vehicles?make=Ford&sort=price-asc&offset=100');
});
it('forgets everything cached before UTC midnight once the day turns', async () => {
const fetchMock = vi.fn().mockImplementation(async () => okResponse());
vi.stubGlobal('fetch', fetchMock);
vi.setSystemTime(new Date('2026-08-16T23:59:30Z'));
await fetchVehicles();
vi.setSystemTime(new Date('2026-08-17T00:00:30Z'));
await fetchVehicles();
expect(fetchMock).toHaveBeenCalledTimes(2);
});
Live from src/lib/data.test.ts, region cache-tests, read from this build at 99df7a8.
Playwright: the real stack, one test at a time
The end-to-end suite drives the real Chrome against both servers, which
the config starts itself, so npm run test:e2e needs nothing running
first. Bids mutate shared API state, so the suite runs serially and resets
the bids before every test. Locators are by role and accessible name
(getByRole('button', { name: 'Load more vehicles' })), which tests what
a visitor sees and keeps the suite honest about accessibility. The URL is
an assertion surface of its own, because the address bar is the app's
state (ADR: The React configuration, explained).
test('tile clicks are GET navigation: URL updates, Back works, deep links restore', async ({
page,
}) => {
await openTheYard(page, '/?status=live&sort=most-bids');
await page.waitForSelector('article');
await page.locator('article h3 button').first().click();
await expect(page).toHaveURL(/vehicle=/);
await expect(page.getByText('Specifications')).toBeVisible();
await expect(page.getByText('Not photographs of this vehicle.')).toBeVisible();
const detailUrl = page.url();
await page.goBack();
await expect(page).not.toHaveURL(/vehicle=/);
await expect(page).toHaveURL(/status=live/);
await expect(page.locator('article').first()).toBeVisible();
await openTheYard(page, detailUrl);
await expect(page.getByText('Specifications')).toBeVisible();
await page.getByRole('button', { name: 'Back to inventory' }).click();
await expect(page).not.toHaveURL(/vehicle=/);
await expect(page.locator('article').first()).toBeVisible();
});
Live from tests/e2e/smoke.spec.ts, region get-navigation, read from this build at 99df7a8.
webServer: [
{
command: process.env.YARD_API_PREBUILT
? 'dotnet run --no-build --project api/TheYard.Api'
: 'npm run api',
env: {
Market__GraceSeconds: '0',
Admin__Key: 'e2e-admin-key',
Admin__VisitorRows: 'true',
Logs__DrainSeconds: '2',
Foreman__Mode: 'recorded',
},
url: 'http://localhost:5210/api/facets',
reuseExistingServer: true,
timeout: 120_000,
},
{
command: process.env.YARD_WEB_PREVIEW
? 'npx vite preview --port 5173 --strictPort'
: 'npm run dev',
url: 'http://localhost:5173',
reuseExistingServer: true,
timeout: 120_000,
},
...(process.env.YARD_RENDER
? [
{
command: 'node render/server.mjs',
env: {
PORT: '5220',
YARD_SITES: 'sql=http://localhost:5173',
YARD_PASS_ORIGIN: 'http://localhost:5173',
YARD_DEADLINE_MS: '20000',
},
url: 'http://localhost:5220/readyz',
reuseExistingServer: true,
timeout: 120_000,
},
]
: []),
],
Live from playwright.config.ts, region web-servers, read from this build at 99df7a8.
The same three, in CI and before every ship
Five CI jobs on every push (the live block below shows them as they are):
the style checks, the frontend suite, the .NET suite with its coverage
count, the database project's build, and the browser suite, which installs
Chrome first. The frontend job also runs tsc -b and the production build,
so a type error fails the run before any test does.
jobs:
style:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v7
with:
ref: ${{ inputs.sha || github.sha }}
- uses: actions/setup-node@v7
with:
node-version: 24
cache: npm
- uses: ./.github/actions/dotnet
- run: npm ci
- run: npm run format:check
- run: npm run lint
- run: npm run format:api:check
frontend:
needs: style
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v7
with:
ref: ${{ inputs.sha || github.sha }}
- uses: actions/setup-node@v7
with:
node-version: 24
cache: npm
- run: npm ci
- run: npx tsc -b
- run: npm run stack:check
- run: npm test
- run: npm run build
api:
needs: style
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v7
with:
ref: ${{ inputs.sha || github.sha }}
- uses: ./.github/actions/dotnet
- name: Run the .NET suites
run: |
set -o pipefail
dotnet test api --collect:"XPlat Code Coverage" --results-directory TestResults \
--filter "Store!=cosmos" \
--logger 'console;verbosity=normal' \
-- DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.Exclude="[TheYard.Infrastructure.Cosmos]*,[TestProject]*" \
DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.ExcludeByAttribute="GeneratedCodeAttribute" \
2>&1 | tee "$RUNNER_TEMP/dotnet-output.txt"
- name: Say which test failed, on the run page
if: failure()
run: |
if [ ! -f "$RUNNER_TEMP/dotnet-output.txt" ]; then
echo "::error::the .NET suites left no output to report"
exit 0
fi
# Three lines after each marker, because the marker is the label and
# the detail is underneath it: "Assert.Contains() Failure" says which
# assertion and the line below it says what was actually in the
# collection, and that second line is the one somebody needs.
grep -E -A 3 '^[[:space:]]*(Failed |Error Message:)' "$RUNNER_TEMP/dotnet-output.txt" \
| grep -v '^--$' \
| head -n 24 \
| while IFS= read -r line; do
printf '::error::%s\n' "$(printf '%s' "$line" | tr -d '\r' | cut -c1-400)"
done
# dotnet writes its totals two different ways depending on the
# logger: one 'Passed! - Failed: 0, Passed: 281 ...' line, or a
# four-line 'Test Run Failed. / Total tests: ...' block. The
# console logger this job asks for produces the second, so a
# pattern that only knew the first printed nothing at all.
grep -E '^[[:space:]]*(Passed!|Failed!|Test Run (Failed|Succeeded)\.|Total tests:|(Passed|Failed|Skipped):[[:space:]]+[0-9]+)' "$RUNNER_TEMP/dotnet-output.txt" \
| head -n 6 | while IFS= read -r line; do
printf '::error::%s\n' "$(printf '%s' "$line" | tr -d '\r' | cut -c1-400)"
done
{
echo '## The .NET suites failed'
echo
echo '```'
grep -E -A 6 '^[[:space:]]*Failed ' "$RUNNER_TEMP/dotnet-output.txt" | head -n 80
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
- name: Count what the tests cover
if: always()
run: python3 .github/coverage.py TestResults 90.0 75.0
- name: The quality ratchet
if: always()
run: python3 .github/quality.py . --ratchet .github/quality-ratchet.json
functions:
needs: style
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v7
with:
ref: ${{ inputs.sha || github.sha }}
- uses: ./.github/actions/dotnet
- name: Run the job hunt Function's tests
run: dotnet restore functions/jobhunt && dotnet test functions/jobhunt.Tests --logger 'console;verbosity=normal'
server:
needs: style
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v7
with:
ref: ${{ inputs.sha || github.sha }}
- uses: ./.github/actions/dotnet
- name: Run the machine lanes' tests
run: dotnet test server/JobHunt.Server.Tests --logger 'console;verbosity=normal'
database:
needs: style
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v7
with:
ref: ${{ inputs.sha || github.sha }}
- uses: ./.github/actions/dotnet
- run: dotnet build api/TheYard.Database/TheYard.Database.sqlproj -c Debug
- name: The build has to have produced a package
run: test -f api/TheYard.Database/bin/Debug/TheYard.Database.dacpac
- run: dotnet build functions/JobHunt.Database/JobHunt.Database.sqlproj -c Debug
- name: The campaign's build has to have produced a package
run: test -f functions/JobHunt.Database/bin/Debug/JobHunt.Database.dacpac
e2e:
needs: style
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v7
with:
ref: ${{ inputs.sha || github.sha }}
- uses: actions/setup-node@v7
with:
node-version: 24
cache: npm
- uses: ./.github/actions/dotnet
- run: npm ci
- run: npx playwright install --with-deps chrome || { test -x /opt/google/chrome/chrome && echo "::warning::the Chrome install could not fetch its system packages; the runner's own Chrome runs the suite"; }
- name: Run the browser suite
run: |
set -o pipefail
npx playwright test 2>&1 | tee "$RUNNER_TEMP/playwright-output.txt"
- name: Say what failed, on the run page
if: failure()
run: |
# Two places, because they are readable by different people.
#
# The step summary is the nice one and it renders only for somebody
# signed in. Annotations are the ones that survive: they come back
# from the public API and show at the top of the run page, which is
# what a person with no login to this repository can actually read.
# The first attempt at this wrote only a summary and taught us that.
if [ ! -f "$RUNNER_TEMP/playwright-output.txt" ]; then
echo "::error::the browser suite left no output to report"
exit 0
fi
# '[Tt]imeout of' rather than 'Timeout of': a test that runs out
# of time says 'Test timeout of 90000ms exceeded.', which the
# capital-only spelling missed, and that line is the whole
# finding when the failure is a hang.
grep -E '^[[:space:]]+[0-9]+\) |Error: |[Tt]imeout of |Timeout: |Locator: |Expected: |Received' "$RUNNER_TEMP/playwright-output.txt" \
| head -n 20 \
| while IFS= read -r line; do
# One annotation per line, trimmed: a control character or a
# newline inside one silently truncates the whole annotation.
printf '::error::%s\n' "$(printf '%s' "$line" | tr -d '\r' | cut -c1-400)"
done
tail -n 4 "$RUNNER_TEMP/playwright-output.txt" | while IFS= read -r line; do
printf '::error::%s\n' "$(printf '%s' "$line" | tr -d '\r' | cut -c1-400)"
done
{
echo '## The browser suite failed'
echo
echo '```'
tail -n 150 "$RUNNER_TEMP/playwright-output.txt"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
- uses: actions/upload-artifact@v7
if: failure()
with:
name: playwright-report
path: playwright-report/
Live from .github/workflows/ci.yml, region ci-jobs, read from this build at 99df7a8.