Saga state machines are useful when a business process needs to continue across multiple messages and services. An order workflow, for example, may start when an order is submitted, continue after payment is confirmed, wait for inventory confirmation, and finish only after all required steps are completed.
Although MassTransit provides a structured way to implement these workflows, a saga can still contain problems that are difficult to identify through normal application testing. A message might not be correlated with the correct saga instance, a state transition might not happen as expected, or an event might be processed while the saga is in an unexpected state. These problems can remain hidden until the application receives real messages.
Testing a saga state machine helps verify that each event produces the expected result. It also helps confirm that the workflow moves through the correct states, publishes the required messages, and handles unexpected situations properly.
MassTransit provides a Test Harness that makes this process easier. It creates an in-memory messaging environment where developers can publish messages, observe consumed and published events, and inspect saga state transitions without connecting to a real message broker.
In this article, we will build a simple order-processing saga and test its behavior using the MassTransit Test Harness in an ASP.NET Core application.
Why Saga State Machine Testing Is Important
A normal unit test usually checks whether a method returns the expected result for a given input. However, a saga state machine is not simply a method that executes from beginning to end. It is a long-running process that reacts to messages over time.
For example, consider an order-processing workflow with the following steps:
- An order is submitted by a customer.
- The saga creates an order workflow instance.
- The payment service confirms that payment has been completed.
- The inventory service confirms that the required items are available.
- The saga completes the order workflow.
Each step may happen at a different time. The application might restart between two events, or messages might arrive in an unexpected order. The saga must preserve its state and continue processing when the next valid event arrives.
Testing only the individual message handlers is not enough to verify the complete workflow. A developer also needs to check whether the messages are correctly correlated, whether the saga enters the expected state, and whether the correct messages are published.
Saga testing is particularly useful for identifying the following problems:
- Incorrect event correlation that creates separate saga instances for the same order.
- State transitions that do not happen after a message is received.
- Messages published more than once because of incorrect workflow behavior.
- Events received in a state where they are not expected.
- Missing business data in the saga instance.
- Incorrect completion behavior that leaves finished workflows active.
- Changes to the state machine that accidentally break an existing workflow.
A good saga test verifies the workflow from the perspective of incoming messages and observable outcomes rather than testing only internal implementation details.
Understanding the MassTransit Test Harness
The MassTransit Test Harness provides an in-memory environment for testing message-based applications. It allows developers to configure consumers, saga state machines, message transports, and repositories without requiring a production message broker.
The test harness provides several useful capabilities:
- It allows tests to publish and send messages through an in-memory bus.
- It records messages consumed by the application.
- It records messages published and sent by the application.
- It supports saga state machine testing.
- It provides access to saga instances created during a test.
- It supports assertions for state machine events and state transitions in supported versions.
- It integrates with dependency injection.
The harness is useful because MassTransit processes messages asynchronously. Instead of immediately checking a result after publishing a message, a test can wait for the expected message to be consumed or published.
For example, a test can publish an OrderSubmitted message and then check whether the saga consumed it. It can also verify that a saga instance was created and moved into the Submitted state.
This approach tests the actual message-processing behavior while keeping the test environment isolated from external infrastructure.
Creating the Order Saga
Before writing tests, we need a simple saga state machine. We will create an order workflow that starts when an order is submitted and moves to the Accepted state after payment confirmation.
The example will use three main components:
- Message contracts that represent incoming business events.
- A saga instance that stores the current workflow state and order information.
- A state machine that defines how the workflow reacts to each event.
Creating Message Contracts
Message contracts define the information exchanged between different parts of the application.
For this example, we need two messages: OrderSubmitted and OrderAccepted.
public record OrderSubmitted
{
public Guid CorrelationId { get; init; }
public string OrderNumber { get; init; } = string.Empty;
public decimal Amount { get; init; }
}
public record OrderAccepted
{
public Guid CorrelationId { get; init; }
public DateTime AcceptedAt { get; init; }
}
Both messages contain a CorrelationId. This property identifies the saga instance associated with the message.
When the first event arrives, MassTransit uses the correlation identifier to create a new saga instance. When the next event arrives, the same identifier allows MassTransit to locate the existing instance and continue the workflow.
Using a consistent correlation identifier is important. If the messages use different identifiers for the same business process, the application may create separate saga instances instead of continuing the original workflow.
Creating the Saga State Instance
The saga state instance stores the information required to continue an order workflow across multiple messages.
using MassTransit;
public class OrderState : SagaStateMachineInstance
{
public Guid CorrelationId { get; set; }
public string CurrentState { get; set; } = string.Empty;
public string OrderNumber { get; set; } = string.Empty;
public decimal Amount { get; set; }
public DateTime? AcceptedAt { get; set; }
}
The OrderState class implements SagaStateMachineInstance. The CorrelationId property identifies the workflow, while CurrentState stores its current state.
The remaining properties contain business information that the saga needs during processing.
For example, the OrderNumber and Amount are copied from the OrderSubmitted message. Later, when the payment confirmation arrives, the saga can update AcceptedAt without requiring the original order information to be sent again.
In a production application, saga state should be stored in a durable repository when workflows need to survive application restarts. We will use an in-memory repository for this testing example because it keeps the test setup simple.
Creating the Saga State Machine
The state machine defines the events, states, and actions that make up the order workflow.
using MassTransit;
public class OrderStateMachine :
MassTransitStateMachine<OrderState>
{
public State Submitted { get; private set; } = null!;
public State Accepted { get; private set; } = null!;
public Event<OrderSubmitted> OrderSubmitted { get; private set; }
= null!;
public Event<OrderAccepted> OrderAccepted { get; private set; }
= null!;
public OrderStateMachine()
{
InstanceState(x => x.CurrentState);
Event(() => OrderSubmitted,
x => x.CorrelateById(context =>
context.Message.CorrelationId));
Event(() => OrderAccepted,
x => x.CorrelateById(context =>
context.Message.CorrelationId));
Initially(
When(OrderSubmitted)
.Then(context =>
{
context.Saga.OrderNumber =
context.Message.OrderNumber;
context.Saga.Amount =
context.Message.Amount;
})
.TransitionTo(Submitted));
During(Submitted,
When(OrderAccepted)
.Then(context =>
{
context.Saga.AcceptedAt =
context.Message.AcceptedAt;
})
.TransitionTo(Accepted));
During(Accepted,
Ignore(OrderAccepted));
}
}
Let's understand how this state machine works.
The InstanceState method connects the state machine's current state to the CurrentState property in the saga instance. MassTransit uses this property to remember the workflow's progress.
The Event methods define how incoming messages are correlated with saga instances. Both events use the CorrelationId from the message.
The Initially section handles the first OrderSubmitted event. When a new order arrives, the state machine copies the order details into the saga instance and moves the workflow into the Submitted state.
The During(Submitted) section handles the next event. When OrderAccepted arrives with the matching CorrelationId, the saga stores the acceptance time and moves into the Accepted state.
The final section ignores another OrderAccepted event after the saga has already reached the Accepted state. This is a simple example of defining behavior for an event that arrives after the workflow has moved forward.
The example is intentionally small so that we can focus on testing. A real order workflow may also include payment failures, inventory checks, compensation actions, timeouts, and finalization.
Installing the Required Test Package
To use the MassTransit Test Harness, add the MassTransit testing package to the test project.
dotnet add package MassTransit.TestFramework
The test project also needs the MassTransit package and the test framework used by your application. For example, if you are using xUnit, install the xUnit packages and the Microsoft test SDK.
Keep the MassTransit package versions consistent across the application and test project. Mixing incompatible versions can lead to dependency or API errors.
The Test Harness is not limited to xUnit. It can also be used with other .NET testing frameworks.
Configuring the Saga Test Harness
The first step in a saga test is registering the state machine with the test harness.
The following example uses xUnit and the in-memory saga repository.
using MassTransit;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
public class OrderSagaTests
{
[Fact]
public async Task Should_start_order_workflow()
{
await using var provider = new ServiceCollection()
.AddMassTransitTestHarness(x =>
{
x.AddSagaStateMachine<
OrderStateMachine,
OrderState>()
.InMemoryRepository();
})
.BuildServiceProvider(true);
var harness = await provider.StartTestHarness();
// Test assertions will be added here.
}
}
The AddMassTransitTestHarness method registers the test harness and configures the in-memory transport. The AddSagaStateMachine method registers the order state machine and its saga instance type.
The InMemoryRepository method configures an in-memory repository for storing saga instances during the test.
The BuildServiceProvider method creates the dependency injection container. The final true argument enables scope validation and helps identify certain dependency injection problems during development.
The StartTestHarness method starts the test environment and returns the harness instance.
The await using statement ensures that the service provider is disposed after the test completes. This also allows the harness and its associated resources to be stopped and cleaned up.
Each test should generally use its own harness. Sharing one harness across unrelated tests can cause messages from one scenario to affect the assertions of another scenario.
Writing Your First Saga Test
Now that the test harness is configured, we can publish an OrderSubmitted message and verify that the saga creates an instance.
[Fact]
public async Task Should_start_order_workflow()
{
await using var provider = new ServiceCollection()
.AddMassTransitTestHarness(x =>
{
x.AddSagaStateMachine<
OrderStateMachine,
OrderState>()
.InMemoryRepository();
})
.BuildServiceProvider(true);
var harness = await provider.StartTestHarness();
var sagaId = Guid.NewGuid();
await harness.Bus.Publish(new OrderSubmitted
{
CorrelationId = sagaId,
OrderNumber = "ORD-1001",
Amount = 2500
});
Assert.True(
await harness.Consumed.Any<OrderSubmitted>());
var sagaHarness = harness
.GetSagaStateMachineHarness<
OrderStateMachine,
OrderState>();
var saga = sagaHarness.Created.ContainsInState(
sagaId,
sagaHarness.StateMachine,
sagaHarness.StateMachine.Submitted);
Assert.NotNull(saga);
Assert.Equal("ORD-1001", saga!.OrderNumber);
Assert.Equal(2500, saga.Amount);
}
This test verifies several important parts of the workflow.
First, it generates a unique CorrelationId for the order. This identifier is used by both the test and the saga state machine.
Next, it publishes the OrderSubmitted message through the test harness bus. Publishing the message starts the asynchronous message-processing flow.
The following assertion checks whether the message was consumed:
Assert.True(
await harness.Consumed.Any<OrderSubmitted>());
This is important because publishing a message does not automatically prove that the saga processed it. The message might not reach the expected endpoint, or the state machine might not be configured correctly.
After verifying message consumption, the test retrieves the saga state machine harness. This provides access to information about the saga instances created during the test.
The ContainsInState method checks whether a saga instance with the specified identifier was created in the Submitted state.
Finally, the test verifies the business data stored in the saga instance.
This test gives us confidence that the initial event was consumed, the saga instance was created, the workflow entered the expected state, and the order information was saved correctly.
Testing State Transitions
Checking whether a saga instance was created is useful, but a workflow usually contains multiple transitions. We also need to verify that the saga moves from one state to another when subsequent messages arrive.
Let's extend the previous scenario.
After publishing OrderSubmitted, the test will publish OrderAccepted with the same CorrelationId.
[Fact]
public async Task Should_move_order_to_accepted_state()
{
await using var provider = new ServiceCollection()
.AddMassTransitTestHarness(x =>
{
x.AddSagaStateMachine<
OrderStateMachine,
OrderState>()
.InMemoryRepository();
})
.BuildServiceProvider(true);
var harness = await provider.StartTestHarness();
var sagaId = Guid.NewGuid();
await harness.Bus.Publish(new OrderSubmitted
{
CorrelationId = sagaId,
OrderNumber = "ORD-1002",
Amount = 3500
});
await harness.Bus.Publish(new OrderAccepted
{
CorrelationId = sagaId,
AcceptedAt = DateTime.UtcNow
});
var sagaHarness = harness
.GetSagaStateMachineHarness<
OrderStateMachine,
OrderState>();
var saga = sagaHarness.Created.ContainsInState(
sagaId,
sagaHarness.StateMachine,
sagaHarness.StateMachine.Submitted);
Assert.NotNull(saga);
var acceptedSaga = sagaHarness.Created.ContainsInState(
sagaId,
sagaHarness.StateMachine,
sagaHarness.StateMachine.Accepted);
Assert.NotNull(acceptedSaga);
Assert.NotNull(acceptedSaga!.AcceptedAt);
}
The test publishes both events using the same CorrelationId. This allows the second event to locate the saga instance created by the first event.
The test then checks whether the workflow reached the Accepted state and whether the acceptance timestamp was stored.
Notice that the test does not call the state machine directly. It sends messages through the test harness, allowing MassTransit to execute the actual message-processing pipeline.
This is an important advantage of the Test Harness. It tests how the application responds to messages instead of only testing isolated state machine methods.
For newer MassTransit versions that support state machine event and transition collections, you can also verify transitions directly.
For example:
Assert.True(
await sagaHarness.StateChanges.Any(
sagaHarness.StateMachine.Submitted,
sagaHarness.StateMachine.Accepted));
This assertion checks whether the saga moved from Submitted to Accepted.
You can also check whether a particular event was observed by the state machine:
Assert.True(
await sagaHarness.Events.Any<OrderAccepted>());
These event and state-change collections are available in MassTransit v9.2 and later. If your project uses an earlier version, use the saga instance and state inspection methods supported by that version.
Testing Published Messages
A saga often publishes events or sends commands to other services. These outgoing messages are an important part of the workflow and should be included in tests.
For example, after an order is accepted, the saga might publish an OrderProcessingStarted event. Another service could consume that event and begin preparing the order.
We can add the following message contract:
public record OrderProcessingStarted
{
public Guid CorrelationId { get; init; }
public string OrderNumber { get; init; } = string.Empty;
}
The state machine can publish this event when the order is accepted.
Update the Accepted behavior as follows:
During(Submitted,
When(OrderAccepted)
.Then(context =>
{
context.Saga.AcceptedAt =
context.Message.AcceptedAt;
})
.Publish(context => new OrderProcessingStarted
{
CorrelationId = context.Saga.CorrelationId,
OrderNumber = context.Saga.OrderNumber
})
.TransitionTo(Accepted));
Now the saga publishes an event after receiving the acceptance message.
We can verify this behavior through the test harness:
Assert.True(
await harness.Published.Any<OrderProcessingStarted>());
This assertion checks whether the expected event was published.
Testing outgoing messages is important because a saga may reach the correct state while still failing to notify the next service. Without this assertion, the test could pass even though the overall business workflow is incomplete.
For more detailed checks, the test can inspect the published message and verify that it contains the expected CorrelationId and OrderNumber.
Testing Invalid or Unexpected Events
Not every message received by a saga represents a valid workflow action. A message may arrive before the workflow has started, or it may arrive after the saga has already moved to another state.
For example, an OrderAccepted message may arrive before OrderSubmitted.
The state machine in our example does not define an initial behavior for OrderAccepted. Therefore, the test should verify that the application does not incorrectly create an order workflow from that event.
[Fact]
public async Task Should_not_create_order_for_acceptance_event()
{
await using var provider = new ServiceCollection()
.AddMassTransitTestHarness(x =>
{
x.AddSagaStateMachine<
OrderStateMachine,
OrderState>()
.InMemoryRepository();
})
.BuildServiceProvider(true);
var harness = await provider.StartTestHarness();
var sagaId = Guid.NewGuid();
await harness.Bus.Publish(new OrderAccepted
{
CorrelationId = sagaId,
AcceptedAt = DateTime.UtcNow
});
var sagaHarness = harness
.GetSagaStateMachineHarness<
OrderStateMachine,
OrderState>();
var saga = sagaHarness.Created.Contains(sagaId);
Assert.Null(saga);
}
This test checks that an acceptance event does not create a new saga instance when the workflow has not started.
It is important to understand that unexpected-event behavior depends on the state machine configuration and the saga repository. Some applications intentionally ignore certain events, while others configure explicit handling or exception behavior.
For production workflows, decide what should happen when an event arrives in an unexpected state. The correct behavior may be to ignore it, publish a rejection event, record an operational warning, or move the message into an error-handling process.
Do not assume that every invalid event should be silently ignored. The expected behavior should be part of the business requirements and should be tested accordingly.
Testing Duplicate Messages
Message brokers and distributed systems can deliver a message more than once. Therefore, saga state machines should be designed with duplicate delivery in mind.
In our example, the state machine ignores OrderAccepted after the saga has already reached the Accepted state.
We can test that behavior by publishing the same acceptance event twice.
[Fact]
public async Task Should_ignore_duplicate_acceptance_event()
{
await using var provider = new ServiceCollection()
.AddMassTransitTestHarness(x =>
{
x.AddSagaStateMachine<
OrderStateMachine,
OrderState>()
.InMemoryRepository();
})
.BuildServiceProvider(true);
var harness = await provider.StartTestHarness();
var sagaId = Guid.NewGuid();
await harness.Bus.Publish(new OrderSubmitted
{
CorrelationId = sagaId,
OrderNumber = "ORD-1003",
Amount = 4500
});
var acceptedAt = DateTime.UtcNow;
await harness.Bus.Publish(new OrderAccepted
{
CorrelationId = sagaId,
AcceptedAt = acceptedAt
});
await harness.Bus.Publish(new OrderAccepted
{
CorrelationId = sagaId,
AcceptedAt = acceptedAt.AddMinutes(1)
});
var sagaHarness = harness
.GetSagaStateMachineHarness<
OrderStateMachine,
OrderState>();
var saga = sagaHarness.Created.ContainsInState(
sagaId,
sagaHarness.StateMachine,
sagaHarness.StateMachine.Accepted);
Assert.NotNull(saga);
Assert.Equal(acceptedAt, saga!.AcceptedAt);
}
The test verifies that the saga remains in the Accepted state and that the second event does not overwrite the original acceptance timestamp.
This is a simple example of duplicate-message protection. In a real application, duplicate handling may require additional checks, especially when an event triggers an external operation such as charging a payment method or reserving inventory.
A state machine test should verify not only that the expected state is reached but also that repeated messages do not produce unwanted business effects.
Testing with a Real Database
The in-memory repository is useful for fast tests, but it does not verify database persistence or database-specific behavior.
For example, an application using Entity Framework Core may encounter problems related to database constraints, concurrency, migrations, or transaction handling that cannot be identified by an in-memory repository test.
A practical testing strategy uses different levels of testing:
- In-memory saga tests for fast verification of state machine behavior.
- Database integration tests for verifying persistence and repository configuration.
- Messaging integration tests for verifying the application with the actual transport and endpoint configuration.
For database integration tests, configure the same saga repository used by the application and run the test against a dedicated test database or an isolated database instance.
The test should create a saga, process another correlated event, and verify that the updated state can be loaded from the repository.
This is particularly important when multiple application instances may process messages concurrently. A database-backed integration test can help verify that the repository configuration and concurrency handling work as expected.
Do not replace every in-memory test with a real database test. Database integration tests take more time and require additional infrastructure. Keep most workflow behavior tests fast, and add integration tests for the persistence and infrastructure behavior that the in-memory repository cannot cover.
Best Practices for Testing Saga State Machines
Use a Separate Test for Each Business Scenario
Each test should focus on one specific behavior, such as starting a workflow, accepting an order, handling an unexpected event, or ignoring a duplicate message.
Avoid creating one large test that covers every possible workflow path. When such a test fails, it becomes difficult to identify the exact behavior that caused the problem.
Use Unique Correlation Identifiers
Generate a new CorrelationId for each test scenario. Reusing identifiers can create confusion when tests share state or when multiple messages are published during the same test.
A unique identifier also makes it easier to trace the messages associated with a particular workflow.
Verify Outcomes Instead of Only Message Consumption
A message being consumed does not prove that the workflow completed correctly.
For example, a test may confirm that OrderAccepted was consumed, but the saga might still be in the Submitted state because a transition was missing.
Check the resulting saga state, stored business data, and published messages to verify the complete behavior.
Test Both Expected and Unexpected Message Sequences
Do not test only the normal workflow. Include scenarios where events arrive in an unexpected order, duplicate events are received, or a required event never arrives.
These scenarios are common in distributed systems and can expose problems that are not visible during normal development.
Keep the Test Harness Isolated
Create a separate test harness for each independent test scenario. The harness maintains asynchronous collections of published, sent, and consumed messages.
Sharing one harness between unrelated scenarios can cause one test's messages to affect another test's assertions.
Use Appropriate Timeouts
The Test Harness uses asynchronous observation collections and configurable test timeouts.
If a test waits for a message that is never published, it will eventually stop waiting based on the configured inactivity or overall timeout.
Avoid increasing timeouts simply to hide slow or unreliable tests. First check whether the message is correctly published, whether the endpoint is configured, and whether the expected behavior is actually triggered.
Keep In-Memory Tests Separate From Infrastructure Tests
An in-memory test is excellent for checking state machine behavior, but it cannot prove that a production database, broker, or deployment configuration works correctly.
Use integration tests where real infrastructure behavior matters. This keeps the test suite both reliable and practical to maintain.
Common Mistakes to Avoid
Checking a Message Immediately After Publishing
MassTransit processes messages asynchronously. Publishing a message and immediately reading the saga repository may happen before the message has been consumed.
Use the Test Harness asynchronous collections and saga inspection methods to wait for the expected behavior.
Testing Only the Initial State
A test that verifies saga creation is useful, but it does not prove that later events work correctly.
Always include tests for important transitions and terminal workflow behavior.
Using Different Correlation Identifiers
If the initial event and subsequent event use different CorrelationId values, the second message will not locate the original saga instance.
Use the same identifier for all events belonging to the same workflow.
Assuming In-Memory Tests Prove Database Reliability
An in-memory repository does not reproduce every behavior of a database-backed repository.
Test database persistence, concurrency, and migrations separately when they are important to the application.
Using Obsolete Test Harness APIs
MassTransit has changed its testing APIs over time. Older examples may use dedicated saga test harness registration methods that are no longer the recommended approach.
For current applications, use AddMassTransitTestHarness and retrieve the saga state machine harness from the main test harness. Always check the documentation for the MassTransit version used by the project.
Conclusion
Testing MassTransit saga state machines is an important part of building reliable message-driven applications. A saga coordinates a business process across multiple messages, so testing only individual consumers or methods does not provide enough confidence in the complete workflow.
The MassTransit Test Harness provides an in-memory environment for testing message consumption, saga creation, state transitions, and outgoing messages. It allows developers to verify how a workflow behaves without requiring a real message broker for every test.
Start by testing the normal business flow, then add scenarios for unexpected events, duplicate messages, and important failure conditions. Use in-memory repositories for fast state machine tests and database integration tests when persistence or concurrency behavior needs to be verified.
A well-tested saga is easier to maintain because changes to message contracts, state transitions, and business rules can be checked before they reach production. It also helps teams identify workflow problems earlier and make distributed applications more predictable.
Join the conversation! Your thoughts help the community grow.