-
Notifications
You must be signed in to change notification settings - Fork 1
Integration MSTest
Local integration guide: A copy of this guide is also available at
docs/integration-mstest.md.
This guide walks you through integrating TestTrackingDiagrams with MSTest. After completing this guide, your MSTest tests will automatically generate:
- PlantUML sequence diagrams from HTTP traffic between your service and its dependencies
- HTML reports with embedded diagrams
- YAML specification files
- .NET 10.0 SDK or later
- An ASP.NET Core API project to test (your "Service Under Test")
- Basic familiarity with MSTest
Create a new MSTest test project:
dotnet new mstest -n MyApi.Tests.Componentdotnet add package TestTrackingDiagrams.MSTest
dotnet add package Microsoft.AspNetCore.Mvc.Testing
dotnet add package Microsoft.NET.Test.Sdk
dotnet add package MSTestMSTest uses [AssemblyInitialize] and [AssemblyCleanup] for global setup and teardown.
using TestTrackingDiagrams;
using TestTrackingDiagrams.MSTest;
namespace MyApi.Tests.Component.Infrastructure;
[TestClass]
public class TestRun : DiagrammedTestRun
{
[AssemblyInitialize]
public static void AssemblyInitialize(TestContext context)
{
Setup();
// Optional: start any HTTP fakes here
}
[AssemblyCleanup]
public static void AssemblyCleanup()
{
EndRunTime = DateTime.UtcNow;
MSTestReportGenerator.CreateStandardReportsWithDiagrams(
TestContexts,
StartRunTime,
EndRunTime,
new ReportConfigurationOptions
{
SpecificationsTitle = "My API Specifications"
});
// Optional: dispose HTTP fakes here
}
}Critical points:
-
[AssemblyInitialize]and[AssemblyCleanup]must bestaticmethods in a class marked with[TestClass]. - Call
Setup()in[AssemblyInitialize]— this records theStartRunTime. - Report generation happens in
[AssemblyCleanup]after all tests have run.
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using TestTrackingDiagrams.MSTest;
namespace MyApi.Tests.Component.Infrastructure;
public abstract class BaseFixture : DiagrammedComponentTest, IDisposable
{
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 MSTestTestTrackingMessageHandlerOptions
{
CallingServiceName = ServiceUnderTestName,
PortsToServiceNames =
{
{ 80, ServiceUnderTestName },
{ 5001, "Downstream Service A" }
}
});
});
});
}
protected BaseFixture()
{
Client = SFactory!.CreateTestTrackingClient(
new MSTestTestTrackingMessageHandlerOptions
{
FixedNameForReceivingService = ServiceUnderTestName
});
}
public void Dispose() => Client.Dispose();
}Key points:
-
DiagrammedComponentTestprovides[TestInitialize](sets the async-local test context) and[TestCleanup](enqueues test metadata for report collection). -
MSTestTestTrackingMessageHandlerOptionsuses the async-localTestContextto resolve the current test's identity.
Tests are written as regular MSTest [TestMethod] methods. Use the [Endpoint] and [HappyPath] attributes to add metadata for the report.
using TestTrackingDiagrams.MSTest;
namespace MyApi.Tests.Component.Scenarios;
[Endpoint("/cake")]
public partial class Cake_Feature
{
[TestMethod]
[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();
}
[TestMethod]
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;
[TestClass]
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);
}
}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.MSTest;
// 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.
┌─────────────────────────────────┐
│ TestRun │ ← [TestClass] with [AssemblyInitialize]/[AssemblyCleanup]
│ : DiagrammedTestRun │ Generates reports in [AssemblyCleanup]
└─────────────────────────────────┘
│
▼
┌─────────────────────────────────┐
│ BaseFixture │ ← Creates tracked HttpClient
│ : DiagrammedComponentTest │ Sets async-local context on [TestInitialize]
│ IDisposable │ Enqueues MSTestScenarioInfo on [TestCleanup]
└─────────────┬───────────────────┘
│ inherited by
▼
┌─────────────────────────────────┐
│ Cake_Feature : BaseFixture │ ← Your test class with [TestMethod] methods
│ [TestClass] │
│ [Endpoint("/cake")] │
└─────────────────────────────────┘
- MSTest's
TestContextis not statically accessible like NUnit'sTestContext.CurrentContextor xUnit v3'sTestContext.Current. TestTrackingDiagrams.MSTest uses anAsyncLocal<TestContext>internally to make the test context available to the HTTP tracking pipeline. - The
[TestInitialize]and[TestCleanup]methods are provided byDiagrammedComponentTest. If your base fixture needs its own initialize/cleanup logic, call the base methods. - For data-driven tests (
[DataRow]), each data row is tracked as a separate scenario in the report.
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