-
Notifications
You must be signed in to change notification settings - Fork 1
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 TestTrackingDiagrams 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 TestTrackingDiagrams.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="TestTrackingDiagrams.xUnit3" Version="1.23.9" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.12" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageReference Include="xunit.v3" Version="1.0.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.0.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>xUnit uses "collection fixtures" to share state across tests. TestTrackingDiagrams provides DiagrammedTestRun as a base class for your collection fixture. This is where reports are generated.
using TestTrackingDiagrams;
using TestTrackingDiagrams.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 TestTrackingDiagrams.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 TestTrackingDiagrams.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
{
CallingServiceName = ServiceUnderTestName,
PortsToServiceNames =
{
{ 80, ServiceUnderTestName },
{ 5001, "Downstream Service A" }
}
});
});
});
}
protected BaseFixture()
{
Client = SFactory!.CreateTestTrackingClient(
new XUnitTestTrackingMessageHandlerOptions
{
FixedNameForReceivingService = ServiceUnderTestName
});
}
public void Dispose(bool disposing) => Client?.Dispose();
}Key points:
-
DiagrammedComponentTestis the library's base class. It applies[Collection("Diagrammed Test Collection")]automatically and enqueues theTestContextonDispose()for report collection. -
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 TestTrackingDiagrams.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). - Class names are converted to feature names: underscores become spaces (e.g.
Cake_Feature→ "Cake Feature"). - Method names are converted to scenario names in the same way.
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 TestTrackingDiagrams.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 boundary between setup and action phases
TrackingDiagramOverride.StartAction();Setup separation: When
SeparateSetup = trueis set onReportConfigurationOptions, HTTP calls made beforeStartAction()are wrapped in a visual "Setup" partition in the diagram.
┌─────────────────────────────────┐
│ 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 |
"Specifications" |
Title shown at the top of reports |
PlantUmlServerBaseUrl |
"https://www.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 |
null |
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 |
|---|---|
CallingServiceName |
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. Unmapped ports appear as localhost_80, localhost_5001, etc. |
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 (blue) 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 TestTrackingDiagrams;
using TestTrackingDiagrams.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(). 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 TestTrackingDiagrams 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.
- 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().
If your SUT makes HTTP calls during startup (hosted services, health probes, warm-up requests), XUnitTestTrackingMessageHandlerOptions will throw NullReferenceException because TestContext.Current.Test is null outside of test execution. The exception is caught internally — tests still pass, but the tracking handler stops working for the affected request pipeline, causing most or all diagrams to be silently missing.
Fix: 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.
Getting Started
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
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
- Search 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
- Diagnostics and Debugging
- CI Summary Integration
- CI Artifact Upload
- Merging Parallel Reports
Reference