Test a workflow
This guide tests the quote workflow from Write a workflow. It fetches a
price, waits up to a day for an approval signal when the quote is over 1000, and sends the quote.
WorkflowTest runs it in memory: it stores the records the workflow actor would store, with no
actor system and no database, so a test takes milliseconds.
The tests are in samples/workflows/fsharp-tests (Expecto) and samples/workflows/csharp-tests
(xUnit). They compile the quote workflow from samples/workflows unchanged, reference the projects
under src/, and need FCQRS.Workflows 7.11.0 or later. Resume, StartAgain, and Recover need
7.12.0.
Give each step's outcome
No activity runs in a test. The test gives each step's outcome, so the services the workflow takes are stand-ins that fail the test if a step calls them:
Shared setup
module Quote =
open System
open System.Threading.Tasks
open FCQRS.Common
open FCQRS.Workflows
// What the workflow is started with.
type QuoteRequest = {
Customer: string
Symbol: string
Quantity: int
}
// What the workflow returns.
type Quote = {
Total: decimal
Approved: bool
Receipt: string
}
// The external systems the workflow calls. Each call gets a key that is the
// same for every attempt of one step, so a system that remembers keys can
// recognise a repeated call.
type IPriceService =
abstract Fetch: key: string * symbol: string -> Task<decimal>
type IMailer =
abstract Send:
key: string * customer: string * total: decimal -> Task<string>
// Five attempts, 200 ms apart, each allowed 30 seconds.
let private retry = {
Retry.times 5 (TimeSpan.FromSeconds 30.0) with
Schedule = FixedInterval(TimeSpan.FromMilliseconds 200.0)
}
let definition (prices: IPriceService) (mailer: IMailer) =
Workflow.define "quote" (fun (request: QuoteRequest) -> workflow {
// The price is stored once it arrives. A restart after this step
// does not call the price service again.
let! price =
activity "price" retry (fun attempt ->
prices.Fetch(attempt.IdempotencyKey, request.Symbol))
let total = price * decimal request.Quantity
// A quote over 1000 waits for a person, for at most one day.
let! approved = workflow {
if total <= 1000m then
return true
else
let! answer =
waitSignalFor<bool> "approval" (TimeSpan.FromDays 1.0)
return defaultArg answer false
}
if not approved then
return { Total = total; Approved = false; Receipt = "" }
else
let! receipt =
activity "send-quote" retry (fun attempt ->
mailer.Send(
attempt.IdempotencyKey, request.Customer, total))
return { Total = total; Approved = true; Receipt = receipt }
})
open System
open Expecto
open FCQRS.Workflows
open Quote
Fcqrs_550-how-to_009-test-a-workflow.md_page.QuoteSystemThreadingTasksFCQRSFCQRS.CommonContains common types like Events and Commands Functionality for Write Side.
WorkflowsFcqrs_550-how-to_009-test-a-workflow.md_page.Quote.QuoteRequestCustomer: stringstringAn abbreviation for the CLI type . Basic Types
Symbol: stringQuantity: intintAn abbreviation for the CLI type . Basic Types
Fcqrs_550-how-to_009-test-a-workflow.md_page.Quote.QuoteTotal: decimaldecimalAn abbreviation for the CLI type . Basic Types
Approved: boolboolAn abbreviation for the CLI type . Basic Types
Receipt: stringFcqrs_550-how-to_009-test-a-workflow.md_page.Quote.IPriceServiceFetch: IPriceService -> string * string -> Task<decimal>keysymbolSystem.Threading.Tasks.Task`1Represents an asynchronous operation that can return a value. The type of the result produced by this .
Fcqrs_550-how-to_009-test-a-workflow.md_page.Quote.IMailerSend: IMailer -> string * string * decimal -> Task<string>customertotalretry: RetryPolicyFCQRS.Workflows.RetryCommon retry policies.
times: int -> TimeSpan -> RetryPolicyAt most `attempts` attempts, with backoff from one second to one minute. Each attempt fails when it has not finished within `attemptTimeout`.
System.TimeSpanRepresents a time interval.
FromSeconds: float -> TimeSpanReturns a that represents a specified number of seconds, where the specification is accurate to the nearest millisecond. A number of seconds, accurate to the nearest millisecond. is less than TimeSpan.MinValue or greater than TimeSpan.MaxValue. -or- is . -or- is . is equal to . An object that represents .
Schedule: RetryScheduleThe wait between attempts.
FixedIntervalRe-send at a fixed interval.
FromMilliseconds: float -> TimeSpanReturns a that represents a specified number of milliseconds. A number of milliseconds. is less than TimeSpan.MinValue or greater than TimeSpan.MaxValue. -or- is . -or- is . is equal to . An object that represents .
definition: IPriceService -> IMailer -> WorkflowDefinition<QuoteRequest,Quote>prices: IPriceServicemailer: IMailerFCQRS.Workflows.WorkflowDefines workflows.
define: string -> ('Input -> Workflow<'Result>) -> WorkflowDefinition<'Input,'Result>A workflow named `name` whose instances run `body` on their input.
request: QuoteRequestworkflow: WorkflowBuilderBuilds a workflow: `workflow { let! x = activity ... }`.
price: decimalactivity: string -> RetryPolicy -> (AttemptContext -> Task<'T>) -> Workflow<'T>Calls an external system. The call runs at least once: a crash after the call and before its result is stored repeats it, so pass `IdempotencyKey` to the external system. `name` is stored and must not change while instances are running. The policy needs an `AttemptTimeout` or a `Deadline`: an attempt with neither would wait as long as its call, also for a call that ignores its cancellation token.
attempt: AttemptContextFetch: string * string -> Task<decimal>IdempotencyKey: stringThe same for every attempt of this step, across restarts: workflow name, workflow ID, and step path. Pass it to the external system so a repeated call is recognised.
total: decimal(*): ^T1 -> ^T2 -> ^T3Overloaded multiplication operator The first parameter. The second parameter. The result of the operation. 8 * 6 // Evaluates to 48
decimal: ^T -> decimalConverts the argument to System.Decimal using a direct conversion for all primitive numeric types. For strings, the input is converted using UInt64.Parse() with InvariantCulture settings. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted decimal. decimal "42.23" // evaluates to 42.23M decimal 0xff // evaluates to 255M decimal -10 // evaluates to -10M
approved: bool(<=): 'T -> 'T -> boolStructural less-than-or-equal comparison The first parameter. The second parameter. The result of the comparison. 5 <= 1 // Evaluates to false 5 <= 5 // Evaluates to true [1; 5] <= [1; 6] // Evaluates to true
answer: bool optionwaitSignalFor: string -> TimeSpan -> Workflow<'T option>Waits for a signal named `name` for at most `timeout`, measured from the stored start of the step. Gives `None` when the time passes first; a signal that arrives later stays stored for the next wait.
FromDays: float -> TimeSpanReturns a that represents a specified number of days, where the specification is accurate to the nearest millisecond. A number of days, accurate to the nearest millisecond. is less than TimeSpan.MinValue or greater than TimeSpan.MaxValue. -or- is . -or- is . is equal to . An object that represents .
defaultArg: 'T option -> 'T -> 'TUsed to specify a default value for an optional argument in the implementation of a function An option representing the argument. The default value of the argument. The argument value. If it is None, the defaultValue is returned. type Vector(x: double, y: double, ?z: double) = let z = defaultArg z 0.0 member this.X = x member this.Y = y member this.Z = z let v1 = Vector(1.0, 2.0) v1.Z // Evaluates to 0. let v2 = Vector(1.0, 2.0, 3.0) v2.Z // Evaluates to 3.0
``not``: bool -> boolNegate a logical value. Not True equals False and not False equals True The value to negate. The result of the negation. not (2 + 2 = 5) // Evaluates to true // not is a function that can be compose with other functions let fileDoesNotExist = System.IO.File.Exists >> not
receipt: stringSend: string * string * decimal -> Task<string>Expecto// No activity runs in a test: the test gives each step's outcome. These
// stand-ins fail the test if one runs anyway.
let private prices = {
new IPriceService with
member _.Fetch(_, _) = failwith "a test runs no activity"
}
let private mailer = {
new IMailer with
member _.Send(_, _, _) = failwith "a test runs no activity"
}
let private quote = definition prices mailer
let private large = { Customer = "Ada"; Symbol = "ABC"; Quantity = 100 }
prices: IPriceServiceFcqrs_550-how-to_009-test-a-workflow.md_page.Quote.IPriceService_: IPriceServiceFetch: string * string -> Threading.Tasks.Task<decimal>failwith: string -> 'TThrow a exception. The exception message. Never returns. let failingFunction() = failwith "Oh no" // Throws an exception true // Never reaches this failingFunction() // Throws a System.Exception
mailer: IMailerFcqrs_550-how-to_009-test-a-workflow.md_page.Quote.IMailer_: IMailerSend: string * string * decimal -> Threading.Tasks.Task<string>quote: WorkflowDefinition<QuoteRequest,Quote>definition: IPriceService -> IMailer -> WorkflowDefinition<QuoteRequest,Quote>large: QuoteRequestCustomer: stringSymbol: stringQuantity: int// No activity runs in a test: the test gives each step's outcome. These
// stand-ins fail the test if one runs anyway.
private sealed class NoPrices : IPriceService
{
public Task<decimal> Fetch(string key, string symbol) =>
throw new InvalidOperationException("a test runs no activity");
}
private sealed class NoMailer : IMailer
{
public Task<string> Send(string key, string customer, decimal total) =>
throw new InvalidOperationException("a test runs no activity");
}
private static readonly QuoteWorkflow Quote =
new(new NoPrices(), new NoMailer());
private static readonly QuoteRequest Large = new("Ada", "ABC", 100);
Test the activities' own code separately, as ordinary functions. These tests check the order of the steps and what the body does with each outcome.
Follow one path through the workflow
let approved =
test "a quote over 1000 is sent once a person approves it" {
let flow = WorkflowTest.Start(quote, large)
flow.Complete("price", 12.5m)
let waits = flow.Status.IsWaitingFor "approval"
Expect.isTrue waits "1250 needs approval"
flow.Signal("approval", true)
flow.Complete("send-quote", "receipt-1")
let expected = { Total = 1250m; Approved = true; Receipt = "receipt-1" }
Expect.equal flow.Result expected "the quote is sent"
// A restart after any stored record must store the same journal.
flow.CheckReplay()
}
approved: Testtest: string -> TestCaseBuilderBuilds a test case
flow: WorkflowTest<QuoteRequest,Quote>FCQRS.Workflows.WorkflowTestRuns workflows in memory, for tests. See `WorkflowTest<'Input, 'Result>`.
Start: WorkflowDefinition<'Input,'Result> * 'Input -> WorkflowTest<'Input,'Result>Starts the workflow with `input` at `WorkflowTest.DefaultStart`.
quote: WorkflowDefinition<QuoteRequest,Quote>large: QuoteRequestComplete: string * 'T -> unitCompletes the waiting activity, command, or child step named `step` with `value`, which is stored and read back as the actor does. A value the step cannot read back fails the step as `NotRetryable`. Raises `InvalidOperationException` when no such step waits, and `ArgumentException` when `value` cannot be stored as the step's result.
waits: boolIsWaitingFor: string -> boolWhether the body is waiting on a step with this name, such as a signal wait, whose step is named after its signal. `false` for an instance that is not running.
Status: WorkflowStatusWhere the instance is, as `Status` reports it for a registered workflow.
Expecto.ExpectA module for specifying what you expect from the values generated by your tests.
isTrue: bool -> string -> unitExpects the value to be true.
Signal: string * 'T -> unitStores a signal, as `Workflows.signal` does. A wait for it takes it, now or when it starts. Raises `InvalidOperationException` when the instance has ended.
expected: QuoteTotal: decimalApproved: boolReceipt: stringequal: 'a -> 'a -> string -> unitExpects the two values to equal each other.
Result: QuoteThe body's result. Raises `WorkflowFaultedException` or `WorkflowCancelledException` when the instance ended otherwise, and `InvalidOperationException` while it has not ended.
CheckReplay: unit -> unitRestarts the instance after every stored record the test produced, gives it the same outcomes, and checks that each restart stores the same journal. Raises `WorkflowReplayException` for the first restart that stores a different record or parks the instance: a body whose steps, stored values, or result change on replay. A pass does not show that the body is deterministic: an activity's arguments are not stored, so a GUID or a time read outside a step that reaches only an activity's call is not seen.
[Fact]
public void A_quote_over_1000_is_sent_once_a_person_approves_it()
{
var flow = WorkflowTest.Start(Quote, Large);
flow.Complete("price", 12.5m);
Assert.True(flow.Status.IsWaitingFor("approval"), "1250 needs approval");
flow.Signal("approval", true);
flow.Complete("send-quote", "receipt-1");
Assert.Equal(new Quote(1250m, true, "receipt-1"), flow.Result);
// A restart after any stored record must store the same journal.
flow.CheckReplay();
}
WorkflowTest.Start stores the input and runs the body until it waits. Each call that follows
stores one record, as the actor would, and runs the body to its next wait:
| Call | Stores |
|---|---|
Complete(step, value) |
the result of the waiting activity, command, or child step with that name |
Fail(step, error) |
the step's failure, as Exhausted; another overload takes the ErrorKind |
Signal(name, value) |
a signal, which a wait for it takes now or when it starts |
Advance(time) |
nothing itself; it moves the clock and fires the timers and timeouts that are due |
Cancel() |
a cancel request and the failure of every waiting step |
Resume() |
a Resumed record: the failed step of a faulted instance waits again |
StartAgain(input) |
a new run, as a start with WorkflowIdReuse.AfterFailure stores it, after a fault or cancel only |
Waiting lists the steps the body waits on, Status reports what a registered workflow's Status
would, and Result gives the body's result once it has ended. Complete raises
InvalidOperationException when no step with that name waits, so a test that gives an outcome too
early fails at that line.
Every value goes through storage. The input, each result, and each signal are stored and read back,
as recovery reads them. A result that replay cannot read fails its step as NotRetryable, as it
would in production.
Move the time
The test's clock starts at WorkflowTest.DefaultStart (1 January 2026, 00:00 UTC) or at the time
given to Start, and moves only with Advance:
let declined =
test "a quote nobody approves within a day is declined" {
let flow = WorkflowTest.Start(quote, large)
flow.Complete("price", 12.5m)
flow.Advance(TimeSpan.FromDays 1.0)
let expected = { Total = 1250m; Approved = false; Receipt = "" }
Expect.equal flow.Result expected "the wait timed out"
flow.CheckReplay()
}
declined: Testtest: string -> TestCaseBuilderBuilds a test case
flow: WorkflowTest<QuoteRequest,Quote>FCQRS.Workflows.WorkflowTestRuns workflows in memory, for tests. See `WorkflowTest<'Input, 'Result>`.
Start: WorkflowDefinition<'Input,'Result> * 'Input -> WorkflowTest<'Input,'Result>Starts the workflow with `input` at `WorkflowTest.DefaultStart`.
quote: WorkflowDefinition<QuoteRequest,Quote>large: QuoteRequestComplete: string * 'T -> unitCompletes the waiting activity, command, or child step named `step` with `value`, which is stored and read back as the actor does. A value the step cannot read back fails the step as `NotRetryable`. Raises `InvalidOperationException` when no such step waits, and `ArgumentException` when `value` cannot be stored as the step's result.
Advance: TimeSpan -> unitMoves the time forward, and fires the timers and signal timeouts that are due by then.
System.TimeSpanRepresents a time interval.
FromDays: float -> TimeSpanReturns a that represents a specified number of days, where the specification is accurate to the nearest millisecond. A number of days, accurate to the nearest millisecond. is less than TimeSpan.MinValue or greater than TimeSpan.MaxValue. -or- is . -or- is . is equal to . An object that represents .
expected: QuoteTotal: decimalApproved: boolReceipt: stringExpecto.ExpectA module for specifying what you expect from the values generated by your tests.
equal: 'a -> 'a -> string -> unitExpects the two values to equal each other.
Result: QuoteThe body's result. Raises `WorkflowFaultedException` or `WorkflowCancelledException` when the instance ended otherwise, and `InvalidOperationException` while it has not ended.
CheckReplay: unit -> unitRestarts the instance after every stored record the test produced, gives it the same outcomes, and checks that each restart stores the same journal. Raises `WorkflowReplayException` for the first restart that stores a different record or parks the instance: a body whose steps, stored values, or result change on replay. A pass does not show that the body is deterministic: an activity's arguments are not stored, so a GUID or a time read outside a step that reaches only an activity's call is not seen.
[Fact]
public void A_quote_nobody_approves_within_a_day_is_declined()
{
var flow = WorkflowTest.Start(Quote, Large);
flow.Complete("price", 12.5m);
flow.Advance(TimeSpan.FromDays(1));
Assert.Equal(new Quote(1250m, false, ""), flow.Result);
flow.CheckReplay();
}
A timer and a signal wait's timeout store their due time when they start, and Advance fires each
one whose due time has passed. A step that reads the time, such as now, reads the test's clock.
Fail a step
let mailerDown =
test "a mailer that stays down faults the quote" {
let flow = WorkflowTest.Start(quote, { large with Quantity = 10 })
flow.Complete("price", 12.5m)
// As if the retry policy's five attempts had failed.
flow.Fail("send-quote", TimeoutException "the mailer is down")
match flow.Status with
| WorkflowStatus.Failed error ->
Expect.equal error.Kind ErrorKind.Exhausted "the attempts ran out"
| other -> failtestf "expected Failed, found %A" other
}
mailerDown: Testtest: string -> TestCaseBuilderBuilds a test case
flow: WorkflowTest<QuoteRequest,Quote>FCQRS.Workflows.WorkflowTestRuns workflows in memory, for tests. See `WorkflowTest<'Input, 'Result>`.
Start: WorkflowDefinition<'Input,'Result> * 'Input -> WorkflowTest<'Input,'Result>Starts the workflow with `input` at `WorkflowTest.DefaultStart`.
quote: WorkflowDefinition<QuoteRequest,Quote>Fcqrs_550-how-to_009-test-a-workflow.md_page.Quote.QuoteRequestlarge: QuoteRequestQuantity: intComplete: string * 'T -> unitCompletes the waiting activity, command, or child step named `step` with `value`, which is stored and read back as the actor does. A value the step cannot read back fails the step as `NotRetryable`. Raises `InvalidOperationException` when no such step waits, and `ArgumentException` when `value` cannot be stored as the step's result.
Fail: string * exn -> unitFails the waiting step named `step` as its retry policy's attempts running out (`Exhausted`).
``.ctor``: string -> unitInitializes a new instance of the class with the specified error message. The message that describes the error.
Status: WorkflowStatusWhere the instance is, as `Status` reports it for a registered workflow.
FCQRS.Workflows.WorkflowStatusWhere a workflow instance is.
FailedThe body threw an exception it did not handle.
error: StepErrorExpecto.ExpectA module for specifying what you expect from the values generated by your tests.
equal: 'a -> 'a -> string -> unitExpects the two values to equal each other.
Kind: ErrorKindFCQRS.Workflows.ErrorKindWhy a step or a workflow ended without a value.
ExhaustedThe retry policy's attempts ran out.
other: WorkflowStatusfailtestf: Printf.StringFormat<'a,'b> -> 'aFail this test
[Fact]
public void A_mailer_that_stays_down_faults_the_quote()
{
var flow = WorkflowTest.Start(Quote, Large with { Quantity = 10 });
flow.Complete("price", 12.5m);
// As if the retry policy's five attempts had failed.
flow.Fail("send-quote", new TimeoutException("the mailer is down"));
var failed = Assert.IsType<WorkflowStatus.Failed>(flow.Status);
Assert.Equal(ErrorKind.Exhausted, failed.Item.Kind);
}
The outcome a test gives is the step's final one. Retry policies are not applied: Fail stands for
the last attempt failing. A command step failed as Exhausted or DeadlineExceeded is stored as
OutcomeUnknown, as the actor stores it.
Check that a restart replays
CheckReplay restarts the instance after every record the test stored, gives it the same outcomes,
and checks that each restart stores the same journal. It raises WorkflowReplayException for the
first restart that differs. That finds a body whose steps, stored values, or result change on
replay, for example because it chooses a step from the clock, a random number, or state outside the
workflow. FCQRS cannot detect such a body while it runs; in production it shows up as a parked
instance.
A passing check does not show that a body is deterministic. The check sees only what the journal
stores, and an activity's arguments are not stored. A body that passes Guid.NewGuid() or
DateTime.UtcNow to an activity sends a different value after each restart, and the check passes.
Read time, GUIDs, and random numbers through now, newGuid, and random, and look for them
outside steps when you review a body.
Restart() does one restart, as the process does after it stops: steps with a stored outcome are
not run again, and a step that was waiting waits again.
Pin the stored steps
Step names, their order, and their kinds are persistent contracts: an instance that is running when
new code is deployed replays its journal against that code. A test of Summary, one line per
stored record, shows a change to them:
let journal =
test "a quote stores the step names that running quotes depend on" {
let flow = WorkflowTest.Start(quote, large)
flow.Complete("price", 12.5m)
flow.Signal("approval", true)
flow.Complete("send-quote", "receipt-1")
let expected = [
"started"
"scheduled 0 price"; "completed 0 price"
"scheduled 1 approval"; "signal approval"; "completed 1 approval"
"scheduled 2 send-quote"; "completed 2 send-quote"
"finished"
]
Expect.equal (List.ofSeq flow.Summary) expected "the stored steps"
}
journal: Testtest: string -> TestCaseBuilderBuilds a test case
flow: WorkflowTest<QuoteRequest,Quote>FCQRS.Workflows.WorkflowTestRuns workflows in memory, for tests. See `WorkflowTest<'Input, 'Result>`.
Start: WorkflowDefinition<'Input,'Result> * 'Input -> WorkflowTest<'Input,'Result>Starts the workflow with `input` at `WorkflowTest.DefaultStart`.
quote: WorkflowDefinition<QuoteRequest,Quote>large: QuoteRequestComplete: string * 'T -> unitCompletes the waiting activity, command, or child step named `step` with `value`, which is stored and read back as the actor does. A value the step cannot read back fails the step as `NotRetryable`. Raises `InvalidOperationException` when no such step waits, and `ArgumentException` when `value` cannot be stored as the step's result.
Signal: string * 'T -> unitStores a signal, as `Workflows.signal` does. A wait for it takes it, now or when it starts. Raises `InvalidOperationException` when the instance has ended.
expected: string listExpecto.ExpectA module for specifying what you expect from the values generated by your tests.
equal: 'a -> 'a -> string -> unitExpects the two values to equal each other.
Microsoft.FSharp.Collections.ListModuleContains operations for working with values of type . Operations for collections such as lists, arrays, sets, maps and sequences. See also F# Collection Types in the F# Language Guide.
ofSeq: 'T seq -> 'T listBuilds a new list from the given enumerable object. The input sequence. The list of elements from the sequence. let inputs = seq { 1; 2; 5 } inputs |> List.ofSeq Evaluates to [ 1; 2; 5 ]. This is an O(n) operation, where n is the length of the sequence.
Summary: Collections.Generic.IReadOnlyList<string>One line per stored record, such as `"scheduled 0 price"` or `"completed 0 price"`: the step's path and name. Step values are in `Journal`.
[Fact]
public void A_quote_stores_the_step_names_that_running_quotes_depend_on()
{
var flow = WorkflowTest.Start(Quote, Large);
flow.Complete("price", 12.5m);
flow.Signal("approval", true);
flow.Complete("send-quote", "receipt-1");
string[] expected =
[
"started",
"scheduled 0 price", "completed 0 price",
"scheduled 1 approval", "signal approval", "completed 1 approval",
"scheduled 2 send-quote", "completed 2 send-quote",
"finished",
];
Assert.Equal(expected, flow.Summary);
}
The path before each name is the step's position in the body. Journal holds the records
themselves, with each stored value. WorkflowTest.Recover(definition, journal) runs code over a
journal another test stored, as a deploy does, and its Status reports Parked when the journal no
longer matches; see Change a workflow while instances are
running.
Run the tests
dotnet run --project samples/workflows/fsharp-tests -c Release
dotnet test samples/workflows/csharp-tests -c Release
All four tests pass in each language.
What these tests leave to you
- The activities' code, and the idempotency key each external system must honour.
- Retry timing and deadlines, which run only on an actor system.
- An aggregate's answer to a command, which a test gives as the step's result. Test the aggregate as Test your domain shows.
- A real restart, with the journal in a database: run the application, stop it in the middle, and start it again, as Write a workflow does.