Class MockContext
A mock Context for unit testing stateless service handlers. Side effects execute inline, calls and sends are recorded for verification.
public sealed class MockContext : Context, IContext
- Inheritance
-
MockContext
- Implements
- Inherited Members
Constructors
MockContext(string?)
Creates a new mock context with the given invocation ID.
public MockContext(string? invocationId = null)
Parameters
invocationIdstring
Properties
Aborted
Cancellation token that fires when the invocation is aborted.
public override CancellationToken Aborted { get; }
Property Value
AwaitedSignals
Signals the handler awaited, in order. Null entries are unnamed signals.
public IReadOnlyList<string?> AwaitedSignals { get; }
Property Value
Calls
All recorded Call invocations.
public IReadOnlyList<RecordedCall> Calls { get; }
Property Value
Cancellations
All recorded CancelInvocation calls (invocation IDs that were cancelled).
public IReadOnlyList<string> Cancellations { get; }
Property Value
Console
Console that is silent during replay to avoid duplicate output.
public override DurableConsole Console { get; }
Property Value
CurrentTime
The time returned by Now(). Set this to control the time in tests. Defaults to 2024-01-01T00:00:00Z.
public DateTimeOffset CurrentTime { get; set; }
Property Value
Headers
Request headers from the original invocation.
public override IReadOnlyDictionary<string, string> Headers { get; }
Property Value
InvocationId
Unique identifier of the current invocation.
public override string InvocationId { get; }
Property Value
Logger
Logger scoped to the current invocation. Output is suppressed while the invocation replays journal entries, so re-executed handler code does not log duplicate lines. Defaults to Instance for custom test doubles; the SDK-provided contexts override it with a replay-aware logger.
public override ILogger Logger { get; }
Property Value
Random
Replay-safe random number generator seeded by the invocation.
public override DurableRandom Random { get; }
Property Value
Sends
All recorded Send invocations.
public IReadOnlyList<RecordedSend> Sends { get; }
Property Value
SignalCompletions
Signals the handler resolved or rejected on other invocations, in order.
public IReadOnlyList<RecordedSignalCompletion> SignalCompletions { get; }
Property Value
Sleeps
All recorded Sleep invocations with their requested durations.
public IReadOnlyList<RecordedSleep> Sleeps { get; }
Property Value
Methods
AllSettled<T>(params ReadOnlySpan<IDurableFuture<T>>)
Awaits all futures and returns a settlement result for each one, in input order.
Unlike All<T>(params ReadOnlySpan<IDurableFuture<T>>), individual failures do not throw — inspect
IsSuccess per item
(matching the TypeScript SDK's RestatePromise.allSettled semantics).
Futures canceled by an invocation abort settle as failures carrying a
TaskCanceledException. Futures pending when the invocation suspends are
never settled as failures — the operations are journaled and WILL complete on a later
attempt, so the suspension propagates instead of fabricating failure entries. A payload
that cannot be deserialized is not a failure entry either: that error propagates so the
attempt is retried.
Inputs are deserialized lazily, each one as the runtime's delivery for it is taken, in delivery order; a failed branch is read from the delivery itself, without decoding a payload.
public override ValueTask<SettledResult<T>[]> AllSettled<T>(params ReadOnlySpan<IDurableFuture<T>> futures)
Parameters
futuresReadOnlySpan<IDurableFuture<T>>
Returns
- ValueTask<SettledResult<T>[]>
Type Parameters
T
All<T>(params ReadOnlySpan<IDurableFuture<T>>)
Awaits all futures and returns their results in order. If any future fails, the first failure in delivery order is thrown as soon as it is delivered, without waiting for the futures still pending; the operations behind them stay journaled and complete there.
Inputs are deserialized lazily: each one is decoded as the runtime's delivery for it is taken, in delivery order, so the decoding order is the one the journal recorded rather than the one the thread pool happens to produce.
A future pending when the invocation suspends is not a failure — the suspension propagates instead, unless another future was delivered a failure, which is thrown in its place because the journal replays it on the next attempt.
public override ValueTask<T[]> All<T>(params ReadOnlySpan<IDurableFuture<T>> futures)
Parameters
futuresReadOnlySpan<IDurableFuture<T>>
Returns
- ValueTask<T[]>
Type Parameters
T
Any<T>(params ReadOnlySpan<IDurableFuture<T>>)
Returns the result of the first future the runtime delivered a successful
result to. Failed futures are ignored unless every future fails, in which case an
AggregateException containing all failures is thrown
(matching the TypeScript SDK's RestatePromise.any / JavaScript AggregateError semantics).
Inputs are inspected in delivery order and only the input handed back is deserialized: a failed branch is read from the delivery itself, without decoding a payload, and a replayed attempt takes the branch the original attempt took.
public override ValueTask<T> Any<T>(params ReadOnlySpan<IDurableFuture<T>> futures)
Parameters
futuresReadOnlySpan<IDurableFuture<T>>
Returns
- ValueTask<T>
Type Parameters
T
Exceptions
- AggregateException
Every future failed (or none were provided); contains each failure as an inner exception, in input order. Futures canceled by an invocation abort count as failures and surface as TaskCanceledException. Futures pending when the invocation suspends are never settled as failures — the suspension propagates instead. A payload that cannot be deserialized is not a failed branch either: that error propagates so the attempt is retried.
Attach<T>(string)
Attaches to a running invocation and awaits its result.
public override ValueTask<T> Attach<T>(string invocationId)
Parameters
invocationIdstring
Returns
- ValueTask<T>
Type Parameters
T
Awakeable<T>(ISerde<T>?)
Creates a durable promise that can be resolved from outside the current invocation.
public override Awakeable<T> Awakeable<T>(ISerde<T>? serde = null)
Parameters
serdeISerde<T>
Returns
- Awakeable<T>
Type Parameters
T
CallFuture<TResponse>(string, string, object?)
Calls a handler and returns a non-blocking future instead of awaiting the result. Use with combinators for concurrent fan-out patterns.
public override IDurableFuture<TResponse> CallFuture<TResponse>(string service, string handler, object? request = null)
Parameters
Returns
- IDurableFuture<TResponse>
Type Parameters
TResponse
CallFuture<TResponse>(string, string, object?, CallOptions)
Calls a handler with call options (idempotency key, scope, limit key) and returns a non-blocking future.
public override IDurableFuture<TResponse> CallFuture<TResponse>(string service, string handler, object? request, CallOptions options)
Parameters
servicestringhandlerstringrequestobjectoptionsCallOptions
Returns
- IDurableFuture<TResponse>
Type Parameters
TResponse
CallFuture<TResponse>(string, string, string, object?)
Calls a handler on a keyed virtual object or workflow and returns a non-blocking future.
public override IDurableFuture<TResponse> CallFuture<TResponse>(string service, string key, string handler, object? request = null)
Parameters
Returns
- IDurableFuture<TResponse>
Type Parameters
TResponse
CallFuture<TResponse>(string, string, string, object?, CallOptions)
Calls a handler on a keyed virtual object or workflow with call options and returns a non-blocking future.
public override IDurableFuture<TResponse> CallFuture<TResponse>(string service, string key, string handler, object? request, CallOptions options)
Parameters
servicestringkeystringhandlerstringrequestobjectoptionsCallOptions
Returns
- IDurableFuture<TResponse>
Type Parameters
TResponse
Call<TResponse>(string, string, object?)
Calls a handler on a stateless service and awaits its response.
public override ValueTask<TResponse> Call<TResponse>(string service, string handler, object? request = null)
Parameters
Returns
- ValueTask<TResponse>
Type Parameters
TResponse
Call<TResponse>(string, string, object?, CallOptions)
Calls a handler on a stateless service with call options (e.g., idempotency key).
public override ValueTask<TResponse> Call<TResponse>(string service, string handler, object? request, CallOptions options)
Parameters
servicestringhandlerstringrequestobjectoptionsCallOptions
Returns
- ValueTask<TResponse>
Type Parameters
TResponse
Call<TResponse>(string, string, string, object?)
Calls a handler on a keyed virtual object or workflow and awaits its response.
public override ValueTask<TResponse> Call<TResponse>(string service, string key, string handler, object? request = null)
Parameters
Returns
- ValueTask<TResponse>
Type Parameters
TResponse
Call<TResponse>(string, string, string, object?, CallOptions)
Calls a handler on a keyed virtual object or workflow with call options.
public override ValueTask<TResponse> Call<TResponse>(string service, string key, string handler, object? request, CallOptions options)
Parameters
servicestringkeystringhandlerstringrequestobjectoptionsCallOptions
Returns
- ValueTask<TResponse>
Type Parameters
TResponse
Call<TRequest, TResponse>(string, string, TRequest, string?)
Calls a handler by service and handler name with typed request/response serialization. Use this when you don't have generated typed clients.
public override ValueTask<TResponse> Call<TRequest, TResponse>(string service, string handler, TRequest request, string? key = null)
Parameters
Returns
- ValueTask<TResponse>
Type Parameters
TRequestTResponse
Call<TRequest, TResponse>(string, string, TRequest, string?, CallOptions)
Calls a handler with typed request/response serialization and call options (idempotency key, scope, limit key).
public override ValueTask<TResponse> Call<TRequest, TResponse>(string service, string handler, TRequest request, string? key, CallOptions options)
Parameters
servicestringhandlerstringrequestTRequestkeystringoptionsCallOptions
Returns
- ValueTask<TResponse>
Type Parameters
TRequestTResponse
CancelInvocation(string)
Cancels a running invocation by sending a cancel signal. The target invocation will be aborted with a cancellation error.
public override ValueTask CancelInvocation(string invocationId)
Parameters
invocationIdstring
Returns
GetOutput<T>(string)
Gets the output of a completed invocation, or default if not yet completed.
public override ValueTask<T?> GetOutput<T>(string invocationId)
Parameters
invocationIdstring
Returns
- ValueTask<T>
Type Parameters
T
Now()
Returns the current time, durably journaled for replay safety.
public override ValueTask<DateTimeOffset> Now()
Returns
ObjectClient<TClient>(string)
Gets a source-generated typed call client for a virtual object, bound to the given key.
public override TClient ObjectClient<TClient>(string key) where TClient : class
Parameters
keystring
Returns
- TClient
Type Parameters
TClient
ObjectSendClient<TClient>(string, SendOptions?)
Gets a source-generated typed send client for a virtual object, bound to the given key.
public override TClient ObjectSendClient<TClient>(string key, SendOptions? options = null) where TClient : class
Parameters
keystringoptionsSendOptions?
Returns
- TClient
Type Parameters
TClient
Race<T>(params ReadOnlySpan<IDurableFuture<T>>)
Returns the result of the future the runtime delivered a result to first.
Only the winner is deserialized: a losing branch is left as the runtime delivered it, so its payload is never decoded and a payload that cannot be decoded cannot fail the invocation. The winner is chosen by delivery order, which makes a replayed attempt take the branch the original attempt took.
public override ValueTask<T> Race<T>(params ReadOnlySpan<IDurableFuture<T>> futures)
Parameters
futuresReadOnlySpan<IDurableFuture<T>>
Returns
- ValueTask<T>
Type Parameters
T
Exceptions
- ArgumentException
No futures were provided.
RegisterClient<TClient>(TClient)
Registers a typed client instance to be returned by ServiceClient<TClient>(), ObjectClient<TClient>(string), or WorkflowClient<TClient>(string).
public void RegisterClient<TClient>(TClient client) where TClient : class
Parameters
clientTClient
Type Parameters
TClient
RejectAwakeable(string, string)
Rejects a previously created awakeable with a failure reason.
public override void RejectAwakeable(string id, string reason)
Parameters
RejectSignal(string, int, string)
Rejects an unnamed signal on another invocation, addressed by its index.
public override ValueTask RejectSignal(string invocationId, int signalIndex, string reason)
Parameters
Returns
RejectSignal(string, string, string)
Rejects a named signal on another invocation: the awaiting handler's future fails with
a TerminalException carrying reason.
public override ValueTask RejectSignal(string invocationId, string name, string reason)
Parameters
Returns
ResolveAwakeable<T>(string, T, ISerde<T>?)
Resolves a previously created awakeable with a payload.
public override void ResolveAwakeable<T>(string id, T payload, ISerde<T>? serde = null)
Parameters
Type Parameters
T
ResolveSignal<T>(string, int, T)
Resolves an unnamed signal on another invocation, addressed by its index (see Signal<T>()).
public override ValueTask ResolveSignal<T>(string invocationId, int signalIndex, T value)
Parameters
Returns
Type Parameters
T
ResolveSignal<T>(string, string, T)
Resolves a named signal on another invocation. The awaiting handler receives
value from its Signal<T>(string) future.
public override ValueTask ResolveSignal<T>(string invocationId, string name, T value)
Parameters
invocationIdstringThe invocation to signal, from an InvocationHandle.
namestringThe signal name the target handler awaits.
valueTThe value the signal resolves with.
Returns
Type Parameters
T
Run(string, Func<IRunContext, Task>)
Executes an async void side effect with a restricted run context.
public override ValueTask Run(string name, Func<IRunContext, Task> action)
Parameters
namestringactionFunc<IRunContext, Task>
Returns
Run(string, Func<Task>)
Executes an async void side effect durably.
public override ValueTask Run(string name, Func<Task> action)
Parameters
Returns
Run(string, Func<Task>, RetryPolicy)
Executes an async void side effect durably with a custom retry policy.
public override ValueTask Run(string name, Func<Task> action, RetryPolicy retryPolicy)
Parameters
namestringactionFunc<Task>retryPolicyRetryPolicy
Returns
RunAsync<T>(string, Func<Task<T>>)
Executes an async side effect and returns a non-blocking future. The action runs immediately but the returned future resolves when the server acknowledges the result. Use with All<T>(params ReadOnlySpan<IDurableFuture<T>>) or Race<T>(params ReadOnlySpan<IDurableFuture<T>>) for concurrent task patterns.
public override IDurableFuture<T> RunAsync<T>(string name, Func<Task<T>> action)
Parameters
Returns
Type Parameters
T
Remarks
The result is the object the action returned on the attempt that ran it, and a copy
deserialized from the journal on every later attempt, so T must
round-trip through the configured serializer and callers must not rely on reference
identity.
Run<T>(string, Func<IRunContext, Task<T>>)
Executes an async side effect with a restricted run context. Prevents nested Restate operations.
public override ValueTask<T> Run<T>(string name, Func<IRunContext, Task<T>> action)
Parameters
namestringactionFunc<IRunContext, Task<T>>
Returns
- ValueTask<T>
Type Parameters
T
Remarks
The result is the object the action returned on the attempt that ran it, and a copy
deserialized from the journal on every later attempt, so T must
round-trip through the configured serializer and callers must not rely on reference
identity.
Run<T>(string, Func<Task<T>>)
Executes an async side effect durably. The result is journaled and replayed on retries.
public override ValueTask<T> Run<T>(string name, Func<Task<T>> action)
Parameters
Returns
- ValueTask<T>
Type Parameters
T
Remarks
The result is the object the action returned on the attempt that ran it, and a copy
deserialized from the journal on every later attempt, so T must
round-trip through the configured serializer and callers must not rely on reference
identity.
Run<T>(string, Func<Task<T>>, RetryPolicy)
Executes an async side effect durably with a custom retry policy. The SDK retries locally with exponential backoff before propagating failures.
public override ValueTask<T> Run<T>(string name, Func<Task<T>> action, RetryPolicy retryPolicy)
Parameters
namestringactionFunc<Task<T>>retryPolicyRetryPolicy
Returns
- ValueTask<T>
Type Parameters
T
Remarks
The result is the object the action returned on the attempt that ran it, and a copy
deserialized from the journal on every later attempt, so T must
round-trip through the configured serializer and callers must not rely on reference
identity.
Run<T>(string, Func<T>)
Executes a synchronous side effect durably. The result is journaled and replayed on retries.
public override ValueTask<T> Run<T>(string name, Func<T> action)
Parameters
Returns
- ValueTask<T>
Type Parameters
T
Remarks
The result is the object the action returned on the attempt that ran it, and a copy
deserialized from the journal on every later attempt, so T must
round-trip through the configured serializer and callers must not rely on reference
identity.
Run<T>(string, Func<T>, RetryPolicy)
Executes a synchronous side effect durably with a custom retry policy. The SDK retries locally with exponential backoff before propagating failures.
public override ValueTask<T> Run<T>(string name, Func<T> action, RetryPolicy retryPolicy)
Parameters
namestringactionFunc<T>retryPolicyRetryPolicy
Returns
- ValueTask<T>
Type Parameters
T
Remarks
The result is the object the action returned on the attempt that ran it, and a copy
deserialized from the journal on every later attempt, so T must
round-trip through the configured serializer and callers must not rely on reference
identity.
Send(string, string, object?, SendOptions)
Sends a one-way invocation to a stateless service with send options (delay, idempotency key, scope, limit key).
public override ValueTask<InvocationHandle> Send(string service, string handler, object? request, SendOptions options)
Parameters
servicestringhandlerstringrequestobjectoptionsSendOptions
Returns
Send(string, string, object?, TimeSpan?, string?)
Sends a one-way invocation to a stateless service. Returns a handle to track the invocation.
public override ValueTask<InvocationHandle> Send(string service, string handler, object? request = null, TimeSpan? delay = null, string? idempotencyKey = null)
Parameters
Returns
Send(string, string, string, object?, SendOptions)
Sends a one-way invocation to a keyed virtual object or workflow with send options.
public override ValueTask<InvocationHandle> Send(string service, string key, string handler, object? request, SendOptions options)
Parameters
servicestringkeystringhandlerstringrequestobjectoptionsSendOptions
Returns
Send(string, string, string, object?, TimeSpan?, string?)
Sends a one-way invocation to a keyed virtual object or workflow. Returns a handle to track the invocation.
public override ValueTask<InvocationHandle> Send(string service, string key, string handler, object? request = null, TimeSpan? delay = null, string? idempotencyKey = null)
Parameters
Returns
Send<TRequest>(string, string, TRequest, string?, SendOptions?)
Sends a one-way invocation by service and handler name with typed request serialization. Returns a handle to track the invocation.
public override ValueTask<InvocationHandle> Send<TRequest>(string service, string handler, TRequest request, string? key = null, SendOptions? options = null)
Parameters
servicestringhandlerstringrequestTRequestkeystringoptionsSendOptions?
Returns
Type Parameters
TRequest
ServiceClient<TClient>()
Gets a source-generated typed call client for a stateless service.
public override TClient ServiceClient<TClient>() where TClient : class
Returns
- TClient
Type Parameters
TClient
ServiceSendClient<TClient>(SendOptions?)
Gets a source-generated typed send client for a stateless service.
public override TClient ServiceSendClient<TClient>(SendOptions? options = null) where TClient : class
Parameters
optionsSendOptions?
Returns
- TClient
Type Parameters
TClient
SetLogger(ILogger)
Sets the logger returned by Logger (and exposed to Run blocks via Logger) so tests can capture handler log output. Defaults to Instance.
public void SetLogger(ILogger logger)
Parameters
loggerILogger
SetupAwakeable<T>(T)
Enqueues a value to be returned by the next Awakeable<T>(ISerde<T>?) call.
Values are consumed in FIFO order. If no value is enqueued, the awakeable resolves
with default(T).
public void SetupAwakeable<T>(T result)
Parameters
resultT
Type Parameters
T
SetupCallFailure(string, string, TerminalException)
Configures a Call to the given service/handler to throw a TerminalException.
public void SetupCallFailure(string service, string handler, TerminalException exception)
Parameters
servicestringhandlerstringexceptionTerminalException
SetupCallFailure(string, string, string, TerminalException)
Configures a Call to the given service/key/handler to throw a TerminalException.
public void SetupCallFailure(string service, string key, string handler, TerminalException exception)
Parameters
servicestringkeystringhandlerstringexceptionTerminalException
SetupCall<T>(string, string, string, T)
Configures the return value for a Call to the given service/key/handler.
public void SetupCall<T>(string service, string key, string handler, T result)
Parameters
Type Parameters
T
SetupCall<T>(string, string, T)
Configures the return value for a Call to the given service/handler.
public void SetupCall<T>(string service, string handler, T result)
Parameters
Type Parameters
T
SetupSignalFailure(string, TerminalException)
Configures the named signal to be rejected with a TerminalException.
public void SetupSignalFailure(string name, TerminalException exception)
Parameters
namestringexceptionTerminalException
SetupSignal<T>(string, T)
Sets the value the named signal resolves with. Without one, the signal resolves with
default(T) so a handler awaiting it still completes in a unit test.
public void SetupSignal<T>(string name, T result)
Parameters
namestringresultT
Type Parameters
T
SetupSignal<T>(T)
Enqueues a value for the next unnamed signal. Values are consumed in the order the handler awaits signals, like SetupAwakeable<T>(T).
public void SetupSignal<T>(T result)
Parameters
resultT
Type Parameters
T
Signal<T>()
Awaits an unnamed signal, addressed by the index this call allocates: the returned SignalHandle<T> carries that index alongside the future. Indices below the first user index are reserved for built-in signals, and they come from the same allocator Awakeable<T>(ISerde<T>?) uses — an awakeable is an unnamed signal plus the opaque id that addresses it, so use Awakeable<T>(ISerde<T>?) when the resolver needs an id to carry around, and this when the resolver addresses the invocation handle and Index.
public override SignalHandle<T> Signal<T>()
Returns
- SignalHandle<T>
Type Parameters
T
Signal<T>(string)
Awaits a signal by name. Another handler holding this invocation handle resolves or rejects the signal by that name, and the returned future composes with All<T>(params ReadOnlySpan<IDurableFuture<T>>), Race<T>(params ReadOnlySpan<IDurableFuture<T>>), Any<T>(params ReadOnlySpan<IDurableFuture<T>>) and AllSettled<T>(params ReadOnlySpan<IDurableFuture<T>>) like any other durable future. A signal resolved before this attempt started resolves from the journal on replay. The ingress addresses signals by awakeable id only, so a named signal has no ingress route — use Awakeable<T>(ISerde<T>?) when an external system must complete it.
public override IDurableFuture<T> Signal<T>(string name)
Parameters
namestringThe signal name the resolver addresses. Must not be empty.
Returns
Type Parameters
T
Sleep(TimeSpan)
Suspends execution for the specified duration. Durable — survives process restarts.
public override ValueTask Sleep(TimeSpan duration)
Parameters
durationTimeSpan
Returns
Timer(TimeSpan)
Creates a non-blocking durable timer that completes after the specified duration. Unlike Sleep(TimeSpan) which blocks, this returns a future for use with combinators.
public override IDurableFuture Timer(TimeSpan duration)
Parameters
durationTimeSpan
Returns
WaitAll(params IDurableFuture[])
Yields futures as the runtime delivers their results, in delivery order. Each element contains the completed future and an optional error. A future canceled by an invocation abort is yielded with a TaskCanceledException as its error rather than with none.
Inputs are deserialized lazily, each one as it is yielded; a failed branch is read from the delivery itself, without decoding a payload. Delivery order is the order the journal recorded, so a replayed attempt yields the futures in the order the original attempt saw them.
public override IAsyncEnumerable<(IDurableFuture future, Exception? error)> WaitAll(params IDurableFuture[] futures)
Parameters
futuresIDurableFuture[]
Returns
WorkflowClient<TClient>(string)
Gets a source-generated typed call client for a workflow, bound to the given key.
public override TClient WorkflowClient<TClient>(string key) where TClient : class
Parameters
keystring
Returns
- TClient
Type Parameters
TClient
WorkflowSendClient<TClient>(string, SendOptions?)
Gets a source-generated typed send client for a workflow, bound to the given key.
public override TClient WorkflowSendClient<TClient>(string key, SendOptions? options = null) where TClient : class
Parameters
keystringoptionsSendOptions?
Returns
- TClient
Type Parameters
TClient