Repository navigation
Integration xUnit3
Example project: A complete working example is available at
examples/Example.Api/tests/Example.Api.Tests.Component.xUnit3/.
This guide walks you through integrating Kronikol with plain xUnit (no BDD framework). After completing this guide, your xUnit tests will automatically generate:
- PlantUML sequence diagrams from HTTP traffic between your service and its dependencies
- HTML reports with embedded diagrams
- YAML specification files
This is the simplest integration path if you are already writing xUnit tests and just want to add automatic diagram generation.
- .NET 10.0 SDK or later
- An ASP.NET Core API project to test (your "Service Under Test")
- Basic familiarity with xUnit
Create a new xUnit test project:
dotnet new xunit -n MyApi.Tests.Componentdotnet add package Kronikol.xUnit3
dotnet add package Microsoft.AspNetCore.Mvc.Testing
dotnet add package Microsoft.NET.Test.Sdk
dotnet add package xunit.v3
dotnet add package xunit.runner.visualstudioYour <ItemGroup> should look like this:
<ItemGroup>
<PackageReference Include="Kronikol.xUnit3" Version="5.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.7" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.3.0" />
<PackageReference Include="xunit.v3" Version="3.2.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>xUnit versions:
Kronikol.xUnit3asks forxunit.v3.extensibility.core3.0.0 or later, so a suite can pin whichever xunit.v3 3.x it runs on. Its own suite runs on the newest 3.x, and in CI on 3.0.0 as well.
xUnit uses "collection fixtures" to share state across tests. Kronikol provides DiagrammedTestRun as a base class for your collection fixture. This is where reports are generated.
using Kronikol;
using Kronikol.xUnit3;
namespace MyApi.Tests.Component.Infrastructure;
public class TestRun : DiagrammedTestRun, IDisposable
{
public TestRun()
{
// Optional: start any HTTP fakes here
}
public void Dispose()
{
EndRunTime = DateTime.UtcNow;
// Generate reports when the test run ends
XUnitReportGenerator.CreateStandardReportsWithDiagrams(
TestContexts,
StartRunTime,
EndRunTime,
new ReportConfigurationOptions
{
SpecificationsTitle = "My API Specifications"
});
// Optional: dispose HTTP fakes here
}
}Create a collection definition that ties all your diagrammed tests to the TestRun fixture:
using Kronikol.xUnit3;
namespace MyApi.Tests.Component;
[CollectionDefinition(DiagrammedComponentTest.DiagrammedTestCollectionName)]
public class DiagrammedTestCollection : ICollectionFixture<Infrastructure.TestRun> { }This class is never instantiated directly — it just tells xUnit to create a single TestRun instance shared across all tests in the collection.
Create Infrastructure/BaseFixture.cs. All your test classes will inherit from this:
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Kronikol.xUnit3;
namespace MyApi.Tests.Component.Infrastructure;
public abstract class BaseFixture : DiagrammedComponentTest
{
private static readonly WebApplicationFactory<Program>? SFactory;
protected HttpClient Client { get; }
private const string ServiceUnderTestName = "My API";
static BaseFixture()
{
SFactory = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
{
builder.ConfigureTestServices(services =>
{
services.TrackDependenciesForDiagrams(new XUnitTestTrackingMessageHandlerOptions
{
CallerName = ServiceUnderTestName,
PortsToServiceNames =
{
{ 80, ServiceUnderTestName },
{ 5001, "Downstream Service A" }
}
});
});
});
}
protected BaseFixture()
{
Client = SFactory!.CreateTestTrackingClient(
new XUnitTestTrackingMessageHandlerOptions
{
FixedNameForReceivingService = ServiceUnderTestName
});
}
public new void Dispose()
{
Client?.Dispose();
base.Dispose();
}
}Key points:
-
DiagrammedComponentTestis the library's base class. It applies[Collection("Diagrammed Test Collection")]automatically and enqueues theTestContextfor report collection onDispose(). xUnit v3 disposes a class that implementsIAsyncLifetime(orIAsyncDisposable) only throughDisposeAsync, so for such a class it enqueues the context after the test instead; before 4.13.3, such a class's tests were missing from the report. -
XUnitTestTrackingMessageHandlerOptionsuses xUnit's built-inTestContext.Currentto resolve the current test's identity.
Tests are written as regular xUnit [Fact] or [Theory] methods. Use the [Endpoint] and [HappyPath] attributes to add metadata for the report.
using Kronikol.xUnit3;
namespace MyApi.Tests.Component.Scenarios;
[Endpoint("/cake")]
public partial class Cake_Feature
{
[Fact]
[HappyPath]
public async Task Calling_Create_Cake_Endpoint_Returns_Cake()
{
await Given_a_valid_post_request_for_the_Cake_endpoint();
await When_the_request_is_sent_to_the_cake_post_endpoint();
await Then_the_response_should_be_successful();
}
[Fact]
public async Task Calling_Create_Cake_Endpoint_Without_Eggs_Returns_Bad_Request()
{
await Given_a_valid_post_request_for_the_Cake_endpoint();
await But_the_request_body_is_missing_eggs();
await When_the_request_is_sent_to_the_cake_post_endpoint();
await Then_the_response_http_status_should_be_bad_request();
}
}using System.Net;
using System.Net.Http.Json;
using MyApi.Tests.Component.Infrastructure;
namespace MyApi.Tests.Component.Scenarios;
public partial class Cake_Feature : BaseFixture
{
private HttpResponseMessage? _response;
private async Task Given_a_valid_post_request_for_the_Cake_endpoint()
{
// Build your request using Client
}
private async Task But_the_request_body_is_missing_eggs()
{
// Modify request
}
private async Task When_the_request_is_sent_to_the_cake_post_endpoint()
{
_response = await Client.PostAsJsonAsync("cake", /* request */);
}
private async Task Then_the_response_should_be_successful()
{
_response!.StatusCode.Should().Be(HttpStatusCode.OK);
}
private async Task Then_the_response_http_status_should_be_bad_request()
{
_response!.StatusCode.Should().Be(HttpStatusCode.BadRequest);
}
}Key points:
-
[Endpoint("/cake")]— Sets the endpoint label for this feature group in the report. -
[HappyPath]— Marks a scenario as a happy path (filterable in the HTML report). -
[Trait("Category", "smoke")]on the method gives the scenario the tagsmoke, and on the class gives it to the feature (5.0.0; see Tags and Attributes › Tags). - Class names are converted to feature names: underscores become spaces (e.g.
Cake_Feature→ "Cake Feature"). - Method names are converted to scenario names as sentences, a word written in capitals kept (5.16.5; see Step Tracking › Method Name Humanization).
- Since 4.14.11 a suite that sets xUnit's
methodDisplayOptions(such asreplaceUnderscoreWithSpace) gets scenarios named after the test method again; from 4.11.1 until then, such a suite's scenario names kept the namespace and class. ADisplayNameis used whole, its own dots and parentheses included, and a theory row's arguments follow the name in brackets (Returns 404 (not found) [id: 1]). Since 5.16.5 aDisplayNameis shown as written, its capitals kept (Order API returns 404 for v1.2, which readOrder api returns 404 for v1.2before), and a name xUnit made from the method reads by the rule on Step Tracking › Method Name Humanization, a word in capitals kept (GetHTTPResponsereadsGet HTTP response). The scenarios keep the stable ids they had.
dotnet testAfter the tests complete, check the bin/Debug/net10.0/Reports/ folder:
| File | Description |
|---|---|
Specifications.html |
HTML specifications with embedded PlantUML sequence diagrams |
TestRunReport.html |
HTML test run report with diagrams and execution summary |
Specifications.yml |
YAML specifications |
You can customise diagrams within a test using TrackingDiagramOverride:
using Kronikol.xUnit3;
// Insert a delimiter between multiple requests in the diagram
TrackingDiagramOverride.InsertTestDelimiter("Step 1");
// Insert raw PlantUML markup
TrackingDiagramOverride.InsertPlantUml("note over MyApi : Custom note");
// Override the start/end of diagram generation
TrackingDiagramOverride.StartOverride();
TrackingDiagramOverride.EndOverride();
// Explicitly mark the beginning of the setup phase (produces a visual separator in the diagram)
TrackingDiagramOverride.StartSetup();
// Explicitly mark the boundary between setup and action phases
TrackingDiagramOverride.StartAction();Setup separation: When
SeparateSetup = trueis set onReportConfigurationOptions, calls made beforeStartAction(), or with Step Tracking before the first[WhenStep]after a[GivenStep], are wrapped in a visual "Setup" partition in the diagram. CallStartSetup()to explicitly mark the beginning of the setup phase.
The Kronikol.xUnit3 package provides a CurrentTestInfo static class whose Fetcher property returns a Func<(string Name, string Id)> delegate that resolves the current test's identity. This is used by all extension CurrentTestInfoFetcher options:
using Kronikol.xUnit3;
options.CurrentTestInfoFetcher = CurrentTestInfo.Fetcher;┌─────────────────────────────────┐
│ DiagrammedTestCollection │ ← Collection definition (one per assembly)
│ ICollectionFixture<TestRun> │
└─────────────┬───────────────────┘
│ creates once
▼
┌─────────────────────────────────┐
│ TestRun │ ← Generates reports in Dispose()
│ : DiagrammedTestRun │
└─────────────────────────────────┘
│ shared across
▼
┌─────────────────────────────────┐
│ BaseFixture │ ← Creates tracked HttpClient
│ : DiagrammedComponentTest │ Enqueues TestContext on Dispose
└─────────────┬───────────────────┘
│ inherited by
▼
┌─────────────────────────────────┐
│ Cake_Feature : BaseFixture│ ← Your test class with [Fact] methods
└─────────────────────────────────┘
| Property | Default | Description |
|---|---|---|
SpecificationsTitle |
"Service Specifications" |
Title shown at the top of reports |
PlantUmlServerBaseUrl |
"https://plantuml.com/plantuml" |
PlantUML server URL |
HtmlSpecificationsFileName |
"Specifications" |
Output filename for specs HTML |
HtmlTestRunReportFileName |
"TestRunReport" |
Output filename for test run HTML |
YamlSpecificationsFileName |
"Specifications" |
Output filename for YAML specs |
HtmlSpecificationsCustomStyleSheet |
Stylesheets.VioletThemeStyleSheet |
Custom CSS appended to specs HTML |
ExcludedHeaders |
[] |
HTTP headers to exclude from diagrams |
SeparateSetup |
false |
When true, HTTP calls made before StartAction() are wrapped in a visual "Setup" partition in the diagram |
HighlightSetup |
true |
When true (and SeparateSetup is enabled), the setup partition is rendered with a background colour |
| Property | Description |
|---|---|
CallerName |
Display name for the service making outgoing HTTP calls |
FixedNameForReceivingService |
Display name for the service receiving requests |
PortsToServiceNames |
Dictionary mapping port numbers to friendly service names. A call no map names appears as its host and port (payments.example.com:443), or localhost:{port} when it goes to this machine. |
When your SUT calls downstream HTTP services, those calls must flow through TestTrackingMessageHandler to produce proper HTTP-style diagram arrows (with method, status code, headers, body). Do not mock service client interfaces and use MessageTracker to manually log HTTP interactions — this produces event-style arrows that are misleading.
Recommended approaches:
-
In-memory fake APIs —
WebApplicationFactoryinstances that serve canned responses (see Example Project) -
JustEat HttpClient Interception — handler-level interception, chain with
TestTrackingMessageHandler -
WireMock.Net — real HTTP server on a random port, map in
PortsToServiceNames
See Tracking Dependencies › Faking Dependencies: Getting Proper HTTP Tracking for detailed examples of each approach.
If your project has multiple xUnit collections, a collection fixture will only capture tests in the "Diagrammed Test Collection" — tests in other collections are silently excluded from reports. xUnit v3's [assembly: AssemblyFixture] solves this by running the fixture once per assembly regardless of collections:
[assembly: AssemblyFixture(typeof(MyApi.Tests.Component.Infrastructure.TestRun))]using Kronikol;
using Kronikol.xUnit3;
namespace MyApi.Tests.Component.Infrastructure;
public class TestRun : DiagrammedTestRun, IDisposable
{
public void Dispose()
{
EndRunTime = DateTime.UtcNow;
XUnitReportGenerator.CreateStandardReportsWithDiagrams(
TestContexts,
StartRunTime,
EndRunTime,
new ReportConfigurationOptions
{
SpecificationsTitle = "My API Specifications"
});
}
}With an assembly fixture, you still need test classes to enqueue their TestContext (either by inheriting from DiagrammedComponentTest or manually — see below), but you no longer need the DiagrammedTestCollection collection definition class or the [Collection] attribute.
When to use: Prefer assembly fixtures over collection fixtures when your project has multiple xUnit collections and you want all tests to contribute to the report.
DiagrammedComponentTest does exactly one thing: call DiagrammedTestRun.TestContexts.Enqueue(TestContext.Current) on Dispose(). For a class that implements IAsyncLifetime, which xUnit v3 disposes only through DisposeAsync, the base class captures such a test after it runs instead (since 4.13.3), and since 4.14.11 calls made in the class's DisposeAsync stay with the test. If your test classes already inherit from a shared fixture (e.g. a domain-specific base class or IClassFixture<T>) and you can't change the inheritance hierarchy, add the enqueue call directly to your existing fixture's teardown:
public class MyExistingBaseFixture : IDisposable
{
// ... existing setup and test infrastructure ...
public void Dispose()
{
// ... existing cleanup ...
// This is the only line needed for Kronikol report collection
DiagrammedTestRun.TestContexts.Enqueue(TestContext.Current);
}
}Or with IAsyncLifetime:
public class MyExistingBaseFixture : IAsyncLifetime
{
public ValueTask InitializeAsync() => ValueTask.CompletedTask;
public ValueTask DisposeAsync()
{
DiagrammedTestRun.TestContexts.Enqueue(TestContext.Current);
return ValueTask.CompletedTask;
}
}Tip: Combine this with an assembly fixture (above) and you don't need
[Collection("Diagrammed Test Collection")]on your test classes at all.
A test skipped by attribute ([Fact(Skip = "...")]), and a test whose constructor, InitializeAsync or class fixture fails, are not in the report: xUnit v3 gives a test class no hook that sees them. A run whose only failures are of that kind has a report with no failures in it, while the runner fails. NUnit 4 and TUnit report such tests since 4.14.4 (see Integration NUnit and Integration TUnit).
- Ensure
TestRun.Dispose()callsXUnitReportGenerator.CreateStandardReportsWithDiagrams. - Ensure your test classes inherit from
BaseFixture(which inherits fromDiagrammedComponentTest). - Ensure you have the
DiagrammedTestCollectioncollection definition class.
- Make sure each test class inherits from
DiagrammedComponentTest(directly or viaBaseFixture). The base class callsDiagrammedTestRun.TestContexts.Enqueue(TestContext.Current)onDispose(); for a class that implementsIAsyncLifetime, the base class captures such a test after it runs (since 4.13.3; since 4.14.11 calls made inDisposeAsyncstay with the test). - A test skipped by attribute, or whose class failed to start, is not in the report: see Known gaps.
If your SUT makes HTTP calls during startup (hosted services, health probes, warm-up requests), XUnitTestTrackingMessageHandlerOptions sets CurrentTestInfoFetcher to read from TestContext.Current.Test, which is null outside of test execution. As of v2.27.10, CurrentTestInfo.Fetcher handles this (since v2.28.22 it throws InvalidOperationException, which the handler catches; it then tries a TestIdentityScope and the global fallback, and sends the call untracked when neither names a test). If you are on an older version, the fetcher threw a NullReferenceException that was caught internally — tests still passed, but the tracking handler stopped working for the affected request pipeline.
Fix (v2.27.9 and earlier): Upgrade to v2.27.10+. If you can't upgrade, use the base TestTrackingMessageHandlerOptions with a null-safe CurrentTestInfoFetcher delegate instead. See HTTP Tracking Setup for the pattern.
If any test has failed, the specifications files will be blank by design. The TestRunReport.html will still be generated.
Home · 🔍 Search this wiki Full-text search across every page. The “Pages” list above matches page and heading names, not page content.
Getting Started
- Quick Start (xUnit)
- Project Templates
- AI Integration Prompt
- Framework Integration Guides
- Migrating to v5
- Migrating to v4
Common Tasks
Integration Guides
- Integration xUnit3
- Integration xUnit2
- Integration NUnit
- Integration MSTest
- Integration TUnit
- Integration BDDfy xUnit3
- Integration LightBDD xUnit2
- Integration LightBDD xUnit3
- Integration LightBDD TUnit
- Integration ReqNRoll xUnit2
- Integration ReqNRoll xUnit3
- Integration ReqNRoll TUnit
- Integration Playwright
Uninstrumentable / polyglot backends
- Integration ProxyTap Extension
- Integration TcpTap Extension
- Integration Otlp Extension
- Exporting to OpenTelemetry
- Ingesting External Captures
- Ingesting from Jest
- Integration Cucumber Messages
- Capture-Time Redaction
Extensions
- Integration AtlasDataApi Extension
- Integration BigQuery Extension
- Integration Bigtable Extension
- Integration BlobStorage Extension
- Integration ClickHouse Extension
- Integration CloudStorage Extension
- Integration CosmosDB Extension
- Integration Dapper Extension
- Integration DynamoDB Extension
- Integration EF Core Relational Extension
- Integration Elasticsearch Extension
- Integration EventBridge Extension
- Integration EventHubs Extension
- Integration Grpc Extension
- Integration Kafka Extension
- Integration MassTransit Extension
- Integration MongoDB Extension
- Integration MySqlConnector Extension
- Integration Npgsql Extension
- Integration Oracle Extension
- Integration PubSub Extension
- Integration Redis Extension
- Integration S3 Extension
- Integration ServiceBus Extension
- Integration SNS Extension
- Integration Spanner Extension
- Integration SqlClient Extension
- Integration Sqlite Extension
- Integration SQS Extension
- Integration StorageQueues Extension
- Integration OpenTelemetry Extension
- Integration DispatchProxy Extension
- Integration MediatR Extension
- Integration PlantUML IKVM
Configuration
- Tracking Dependencies
- Tracking Custom Dependencies
- HTTP Tracking Setup
- Report Configuration
- Diagram Customisation
- Phase-Aware Tracking
- Content Formatting
- PlantUML Server Configuration
Features
- Generated Reports
- Report Themes
- Search and Filter Syntax
- Component Diagrams
- PlantUML Browser Rendering
- Inline SVG Rendering
- Internal Flow Tracking
- Tags and Attributes
- Excluding Requests
- Excluded Headers
- Multi-Host Test Architectures
- Event-Driven Architecture Testing
- Service Bus Tracking Patterns
- Background Thread Correlation
- Parallel-Safe Background Correlation
- Event & Message Tracking
- Assertion Tracking
- Step Tracking
- Tabular Attributes
- Large Response and Diagram Handling
- Querying Reports
- Service Card
- Cross-Run History
- Diagnostics and Debugging
- CI Summary Integration
- CI Artifact Upload
- Merging Parallel Reports
Reference