{"id":17298681,"url":"https://github.com/mauroservienti/nservicebus.integrationtesting","last_synced_at":"2026-03-03T22:07:34.712Z","repository":{"id":39758707,"uuid":"195016910","full_name":"mauroservienti/NServiceBus.IntegrationTesting","owner":"mauroservienti","description":"An end-to-end testing toolkit for NServiceBus based messaging systems.","archived":false,"fork":false,"pushed_at":"2025-02-13T11:42:52.000Z","size":739,"stargazers_count":7,"open_issues_count":19,"forks_count":2,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-04-14T11:41:43.128Z","etag":null,"topics":["hacktoberfest","testing"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mauroservienti.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-07-03T08:57:38.000Z","updated_at":"2025-02-13T11:42:56.000Z","dependencies_parsed_at":"2024-10-29T21:01:51.166Z","dependency_job_id":null,"html_url":"https://github.com/mauroservienti/NServiceBus.IntegrationTesting","commit_stats":null,"previous_names":[],"tags_count":13,"template":false,"template_full_name":"mauroservienti/code-repo-template","purl":"pkg:github/mauroservienti/NServiceBus.IntegrationTesting","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mauroservienti%2FNServiceBus.IntegrationTesting","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mauroservienti%2FNServiceBus.IntegrationTesting/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mauroservienti%2FNServiceBus.IntegrationTesting/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mauroservienti%2FNServiceBus.IntegrationTesting/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mauroservienti","download_url":"https://codeload.github.com/mauroservienti/NServiceBus.IntegrationTesting/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mauroservienti%2FNServiceBus.IntegrationTesting/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":266450585,"owners_count":23930554,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-07-22T02:00:09.085Z","response_time":66,"last_error":null,"robots_txt_status":null,"robots_txt_updated_at":null,"robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["hacktoberfest","testing"],"created_at":"2024-10-15T11:19:45.155Z","updated_at":"2026-03-03T22:07:34.705Z","avatar_url":"https://github.com/mauroservienti.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# NServiceBus.IntegrationTesting\n\nNServiceBus.IntegrationTesting enables testing end-to-end business scenarios against real production endpoints, real transports, and real persistence.\n\n\u003e [!IMPORTANT]\n\u003e **Disclaimer**: NServiceBus.IntegrationTesting is not affiliated with Particular Software and is not officially supported by Particular Software.\n\n\u003e [!NOTE]\n\u003e Version 3 is a major rewrite with a new out-of-process architecture. Pre-release packages are available via the [Feedz.io pre-releases feed](https://f.feedz.io/mauroservienti/pre-releases/nuget/index.json).\n\n---\n\n## Prerequisites\n\n- [Docker](https://www.docker.com/products/docker-desktop/) installed and running — all endpoints and infrastructure run in containers\n- .NET 8 or .NET 10 SDK\n\n## Installation\n\nInstall the core test-host package into your test project:\n\n```\ndotnet add package NServiceBus.IntegrationTesting\n```\n\nAdd infrastructure extension packages for the transports and persistence your endpoints use:\n\n```\ndotnet add package NServiceBus.IntegrationTesting.RabbitMQ     # RabbitMQ transport\ndotnet add package NServiceBus.IntegrationTesting.PostgreSql   # PostgreSQL persistence or transport\ndotnet add package NServiceBus.IntegrationTesting.MySql        # MySQL persistence\ndotnet add package NServiceBus.IntegrationTesting.SqlServer    # SQL Server persistence or transport\ndotnet add package NServiceBus.IntegrationTesting.MongoDb      # MongoDB persistence\ndotnet add package NServiceBus.IntegrationTesting.RavenDb      # RavenDB persistence\n```\n\nInstall the agent package into each `*.Testing` companion project, matching the NServiceBus version that endpoint uses:\n\n| NServiceBus version | Agent package | Target framework |\n|---|---|---|\n| 10 | `NServiceBus.IntegrationTesting.AgentV10` | net10.0 |\n| 9 | `NServiceBus.IntegrationTesting.AgentV9` | net8.0 |\n| 8 | `NServiceBus.IntegrationTesting.AgentV8` | net6.0 |\n\n```\ndotnet add package NServiceBus.IntegrationTesting.AgentV10   # for NServiceBus 10 endpoints\ndotnet add package NServiceBus.IntegrationTesting.AgentV9    # for NServiceBus 9 endpoints\ndotnet add package NServiceBus.IntegrationTesting.AgentV8    # for NServiceBus 8 endpoints\n```\n\n---\n\n## Architecture: out-of-process with Docker containers\n\nEach endpoint runs in its own Docker container. Endpoints can run **different NServiceBus major versions** side-by-side. The test process acts as a gRPC server; each endpoint embeds a lightweight gRPC agent that connects home on startup.\n\n### How it works\n\n```\nTest process\n└─ TestHostServer (gRPC, dynamic port)\n   ├─[bidirectional streaming]─► SampleEndpoint container (NSB 10 / .NET 10)\n   │                                └─► RabbitMQ container\n   │                                └─► PostgreSQL container\n   └─[bidirectional streaming]─► AnotherEndpoint container (NSB 9 / .NET 8)\n                                     └─► RabbitMQ container\n```\n\n### Writing a test\n\n\u003c!-- snippet: writing-a-test --\u003e\n\u003ca id='snippet-writing-a-test'\u003e\u003c/a\u003e\n```cs\n[TestFixture]\npublic class WhenSomeMessageIsSent\n{\n    static TestEnvironment _env = null!;\n\n    [OneTimeSetUp]\n    public static async Task SetUp()\n    {\n        var srcDir = Path.Combine(FindRepoRoot(), \"src\");\n\n        _env = await new TestEnvironmentBuilder()\n            .WithDockerfileDirectory(srcDir)\n            .UseRabbitMQ()\n            .UsePostgreSql()\n            .AddEndpoint(\"SampleEndpoint\", \"SampleEndpoint.Testing/Dockerfile\")\n            .AddEndpoint(\"AnotherEndpoint\", \"AnotherEndpoint.Testing/Dockerfile\")\n            .StartAsync();\n    }\n\n    [OneTimeTearDown]\n    public static Task TearDown() =\u003e _env.DisposeAsync().AsTask();\n\n    [Test]\n    public async Task The_full_chain_should_be_processed()\n    {\n        var correlationId = await _env.GetEndpoint(\"SampleEndpoint\")\n            .ExecuteScenarioAsync(\"SomeMessage\", new Dictionary\u003cstring, string\u003e\n            {\n                { \"ID\", Guid.NewGuid().ToString() }\n            });\n\n        using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));\n\n        var results = await _env.Observe(correlationId, cts.Token)\n            .HandlerInvoked(\"SomeMessageHandler\")\n            .HandlerInvoked(\"AnotherMessageHandler\")\n            .HandlerInvoked(\"SomeReplyHandler\")\n            .WhenAllAsync();\n\n        Assert.Multiple(() =\u003e\n        {\n            Assert.That(results.HandlerInvoked(\"SomeMessageHandler\").EndpointName,\n                Is.EqualTo(\"SampleEndpoint\"));\n            Assert.That(results.HandlerInvoked(\"AnotherMessageHandler\").EndpointName,\n                Is.EqualTo(\"AnotherEndpoint\"));\n        });\n    }\n\n    [Test]\n    public async Task A_failing_message_is_reported()\n    {\n        var correlationId = await _env.GetEndpoint(\"SampleEndpoint\")\n            .ExecuteScenarioAsync(\"FailingMessage\", new Dictionary\u003cstring, string\u003e\n            {\n                { \"ID\", Guid.NewGuid().ToString() }\n            });\n\n        using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));\n\n        var results = await _env.Observe(correlationId, cts.Token)\n            .MessageFailed()\n            .WhenAllAsync();\n\n        var failure = results.MessageFailed();\n        Assert.That(failure.EndpointName, Is.EqualTo(\"AnotherEndpoint\"));\n        Assert.That(failure.ExceptionMessage, Does.Contain(\"Intentional failure\"));\n    }\n\n    static string FindRepoRoot()\n    {\n        var dir = new DirectoryInfo(AppContext.BaseDirectory);\n        while (dir is not null \u0026\u0026 !dir.GetDirectories(\".git\").Any())\n            dir = dir.Parent;\n        return dir?.FullName\n            ?? throw new InvalidOperationException(\n                \"Cannot locate repository root. Ensure the test runs inside a git repository.\");\n    }\n}\n```\n\u003csup\u003e\u003ca href='/src/Snippets/TestFixtureSnippets.cs#L6-L85' title='Snippet source file'\u003esnippet source\u003c/a\u003e | \u003ca href='#snippet-writing-a-test' title='Start of snippet'\u003eanchor\u003c/a\u003e\u003c/sup\u003e\n\u003c!-- endSnippet --\u003e\n\n\u003e [!NOTE]\n\u003e The example uses **NUnit** (`[TestFixture]`, `[OneTimeSetUp]`, `Assert.Multiple`). xUnit or MSTest users need to adapt the fixture lifecycle and assertion calls accordingly.\n\n`FindRepoRoot()` is a helper you write once in your test project. It walks up from the test output directory until it finds a marker — `.git`, a `.sln` file, or any other anchor that matches where your Dockerfiles are rooted — giving `TestEnvironmentBuilder` a stable base path regardless of where `dotnet test` is invoked from.\n\n\u003c!-- Intentionally not a relative link, since this README is also included in the NuGet package --\u003e\nFor a full walkthrough and API reference, see the **[documentation](https://github.com/mauroservienti/NServiceBus.IntegrationTesting/blob/master/docs/README.md)** or the **[getting started guide](https://github.com/mauroservienti/NServiceBus.IntegrationTesting/blob/master/docs/getting-started.md)**.\n\n### Key concepts\n\n**`TestEnvironmentBuilder`** — fluent builder that starts a Docker network, infrastructure containers, the gRPC test host, and all endpoint containers. Optionally adds [WireMock.Net](https://github.com/WireMock-Net/WireMock.Net) for HTTP stubbing via `.UseWireMock()`. It automatically injects `NSBUS_TESTING_HOST` into every endpoint container so the agent knows where to connect — endpoints do not configure this themselves.\n\n**Scenarios** — named entry points defined in the `*.Testing` companion project. A scenario runs _inside the endpoint process_, using the real `IMessageSession`, so no cross-process message serialization occurs:\n\n\u003c!-- snippet: scenario --\u003e\n\u003ca id='snippet-scenario'\u003e\u003c/a\u003e\n```cs\npublic class SomeMessageScenario : Scenario\n{\n    public override string Name =\u003e \"SomeMessage\";\n\n    public override async Task Execute(IMessageSession session,\n        Dictionary\u003cstring, string\u003e args, CancellationToken cancellationToken = default)\n        =\u003e await session.Send(new SomeMessage { Id = Guid.Parse(args[\"ID\"]) });\n}\n```\n\u003csup\u003e\u003ca href='/src/Snippets/ScenarioSnippets.cs#L7-L16' title='Snippet source file'\u003esnippet source\u003c/a\u003e | \u003ca href='#snippet-scenario' title='Start of snippet'\u003eanchor\u003c/a\u003e\u003c/sup\u003e\n\u003c!-- endSnippet --\u003e\n\n**`ObserveContext`** — fluent API for waiting on events correlated by scenario invocation. Register all conditions before calling `.WhenAllAsync()` — the same method names serve double duty: called on the builder they register a condition; called on the returned `ObserveResults` they retrieve the matched event. If the cancellation token fires before all conditions are met, `WhenAllAsync()` throws `OperationCanceledException`. Each condition type supports no-arg, single-event predicate, and list predicate overloads.\n\n| Condition | Key result properties |\n|---|---|\n| `.HandlerInvoked(name)` | `.EndpointName` |\n| `.SagaInvoked(name)` | `.EndpointName`, `.SagaIsNew`, `.SagaIsCompleted` |\n| `.MessageDispatched(name)` | `.EndpointName`, `.Intent` (e.g. `\"Publish\"`, `\"Send\"`) |\n| `.MessageFailed()` | `.EndpointName`, `.ExceptionMessage` |\n\n**Production / testing separation** — production endpoints have zero testing dependencies. Each endpoint has a companion `*.Testing` project that wraps the production config with `IntegrationTestingBootstrap` and registers scenarios.\n\n### Why `*.Testing` companion projects?\n\nThe production endpoint (`SampleEndpoint/`) has no reference to any testing library. It stays clean and deployable as-is.\n\nThe `*.Testing` companion project exists solely for integration tests. It:\n\n1. **Wraps the production config** — calls the same `Config.Create()` factory used in\n   production, then overlays test-specific settings (e.g. shorter retry counts so failing\n   messages reach the error queue quickly instead of spending minutes in retry loops).\n2. **Registers scenarios** — named entry points that run _inside_ the endpoint process\n   using the real `IMessageSession`. Because scenarios execute in-process, messages are\n   created and sent natively — no cross-process serialization, no test-only message\n   constructors, no leaking of test concerns into production types.\n3. **Provides the Dockerfile** — builds a container image from the companion project, not\n   from the production project. Only the testing image carries the agent and scenario\n   registrations. A minimal `Dockerfile` (build context: `src/`) looks like:\n\n```dockerfile\nFROM mcr.microsoft.com/dotnet/sdk:10.0 AS build\nWORKDIR /src\n\nCOPY YourMessages/YourMessages.csproj YourMessages/\nCOPY YourEndpoint/YourEndpoint.csproj YourEndpoint/\nCOPY YourEndpoint.Testing/YourEndpoint.Testing.csproj YourEndpoint.Testing/\nRUN dotnet restore YourEndpoint.Testing/YourEndpoint.Testing.csproj\n\nCOPY YourMessages/ YourMessages/\nCOPY YourEndpoint/ YourEndpoint/\nCOPY YourEndpoint.Testing/ YourEndpoint.Testing/\nRUN dotnet publish YourEndpoint.Testing/YourEndpoint.Testing.csproj -c Release -o /app/publish\n\nFROM mcr.microsoft.com/dotnet/runtime:10.0\nWORKDIR /app\nCOPY --from=build /app/publish .\nENTRYPOINT [\"dotnet\", \"YourEndpoint.Testing.dll\"]\n```\n\n```text\nSampleEndpoint/                  ← production code, zero test dependencies\nSampleEndpoint.Testing/          ← wraps production config, adds agent + scenarios\n  Program.cs                     ← IntegrationTestingBootstrap.RunAsync(...)\n  SomeMessageScenario.cs         ← implements Scenario base class\n  Dockerfile                     ← builds the testable container image\nSampleEndpoint.Tests/            ← NUnit test project, references Testing only for\n  WhenSomeMessageIsSent.cs         compile-time validation (ReferenceOutputAssembly=false)\n```\n\nThe test project references the `*.Testing` project with `ReferenceOutputAssembly=\"false\"`. This gives compile-time validation that the `*.Testing` project builds, while at test runtime the container image is built from its Dockerfile — there is no in-process loading of the endpoint assembly.\n\n## NuGet packages\n\n| Package | Purpose |\n|---|---|\n| `NServiceBus.IntegrationTesting` | Test host, `TestEnvironmentBuilder`, observe API |\n| `NServiceBus.IntegrationTesting.RabbitMQ` | RabbitMQ transport container |\n| `NServiceBus.IntegrationTesting.PostgreSql` | PostgreSQL persistence container |\n| `NServiceBus.IntegrationTesting.MySql` | MySQL persistence container |\n| `NServiceBus.IntegrationTesting.SqlServer` | SQL Server persistence container |\n| `NServiceBus.IntegrationTesting.MongoDb` | MongoDB persistence container |\n| `NServiceBus.IntegrationTesting.RavenDb` | RavenDB persistence container |\n| `NServiceBus.IntegrationTesting.AgentV10` | Agent for NServiceBus 10 (net10.0) |\n| `NServiceBus.IntegrationTesting.AgentV9` | Agent for NServiceBus 9 (net8.0) |\n| `NServiceBus.IntegrationTesting.AgentV8` | Agent for NServiceBus 8 (net6.0) |\n\n- [NuGet stable releases](https://www.nuget.org/packages/NServiceBus.IntegrationTesting)\n- [Feedz.io pre-releases feed](https://f.feedz.io/mauroservienti/pre-releases/nuget/index.json)\n\n---\n\nIcon [test](https://thenounproject.com/search/?q=test\u0026i=2829166) by Andrei Yushchenko from the Noun Project\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmauroservienti%2Fnservicebus.integrationtesting","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmauroservienti%2Fnservicebus.integrationtesting","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmauroservienti%2Fnservicebus.integrationtesting/lists"}