Reference

Testing


orcher_sdk::testing runs workflows in memory, with no server: tasks are answered by mocks, so a test checks the workflow's own logic. It is part of the default features (testing). Use #[tokio::test] for async tests.

The examples test this workflow:

1
use orcher_sdk::prelude::*;
2
3
#[derive(Clone, Serialize, Deserialize)]
4
pub struct Order {
5
pub order_id: String,
6
pub items: Vec<u64>,
7
}
8
9
#[derive(Debug, PartialEq, Serialize, Deserialize)]
10
pub struct Receipt {
11
pub order_id: String,
12
pub charge_id: String,
13
pub total_cents: u64,
14
}
15
16
/// Plain logic, tested without any Orcher type.
17
pub fn total_cents(items: &[u64]) -> u64 {
18
items.iter().sum()
19
}
20
21
#[task(retry = 3)]
22
pub async fn charge_card(_ctx: TaskContext, amount_cents: u64) -> Result<String> {
23
// Call your payment provider here.
24
Ok(format!("ch_{amount_cents}"))
25
}
26
27
#[task]
28
pub async fn email_receipt(_ctx: TaskContext, receipt: Receipt) -> Result<bool> {
29
// Send the email here.
30
Ok(!receipt.charge_id.is_empty())
31
}
32
33
#[workflow]
34
pub async fn checkout(ctx: WorkflowContext, order: Order) -> Result<Receipt> {
35
let total = total_cents(&order.items);
36
let charge_id: String = ctx.execute_task(charge_card, total).await?;
37
let receipt = Receipt {
38
order_id: order.order_id,
39
charge_id,
40
total_cents: total,
41
};
42
let _sent: bool = ctx
43
.execute_task(
44
email_receipt,
45
Receipt {
46
order_id: receipt.order_id.clone(),
47
charge_id: receipt.charge_id.clone(),
48
total_cents: receipt.total_cents,
49
},
50
)
51
.await?;
52
Ok(receipt)
53
}

Testing a Workflow with Mocked Tasks

TestWorkflowExecutor runs a workflow function and answers each task it schedules from a MockRegistry. It runs the workflow, collects the tasks it scheduled, runs their mocks, and replays the workflow with the results, until the workflow returns.

1
use super::*;
2
use orcher_sdk::testing::{MockRegistry, MockTaskBuilder, TestWorkflowExecutor};
3
use orcher_sdk::workflow::WorkflowExecution;
4
use std::sync::{Arc, RwLock};
5
6
fn execution() -> WorkflowExecution {
7
WorkflowExecution::new(
8
"order-1".to_string(), // workflow id
9
"run-1".to_string(), // run id
10
"checkout".to_string(),
11
"default".to_string(), // namespace
12
"orders".to_string(), // task queue
13
)
14
}
15
16
#[tokio::test]
17
async fn charges_the_order_total() -> Result<()> {
18
let mocks = Arc::new(RwLock::new(MockRegistry::new()));
19
// Mocks are keyed by task name. Pass the success value itself.
20
MockTaskBuilder::new("charge_card".to_string(), mocks.clone()).returns("ch_test");
21
MockTaskBuilder::new("email_receipt".to_string(), mocks.clone()).returns(true);
22
23
let order = Order {
24
order_id: "ord_1".to_string(),
25
items: vec![1_500, 2_500],
26
};
27
let receipt: Receipt = TestWorkflowExecutor::new(mocks)
28
.execute_workflow(checkout, execution(), order)
29
.await?;
30
31
assert_eq!(receipt.charge_id, "ch_test");
32
assert_eq!(receipt.total_cents, 4_000);
33
Ok(())
34
}
  • Pass the #[workflow] function itself; the macro keeps it callable.
  • Mocks are keyed by the task's registered name, and every task the workflow reaches needs one.
  • WorkflowExecution::new takes the workflow id, run id, workflow type, namespace and task queue that ctx reports.
  • with_max_steps(n) limits how many times the workflow is run (1000 by default), which catches a workflow that never finishes.

Mocking Tasks

MockTaskBuilder::new(task_name, registry) registers one mock:

MethodThe mock
returns(value)Returns value on every call. Pass the success value, not a Result.
returns_seq(vec![...])Returns the next value on each call, and fails once they run out
with_fn(function)Computes the result from the task's input; the function takes and returns JSON bytes
fails_with(message)Fails on every call

A function mock can check the input the workflow passed and count calls:

1
#[tokio::test]
2
async fn charges_once_with_the_total() -> Result<()> {
3
use std::sync::atomic::{AtomicUsize, Ordering};
4
5
let mocks = Arc::new(RwLock::new(MockRegistry::new()));
6
let calls = Arc::new(AtomicUsize::new(0));
7
let seen = Arc::clone(&calls);
8
// A function mock gets the task's JSON input and returns JSON.
9
MockTaskBuilder::new("charge_card".to_string(), mocks.clone()).with_fn(move |input| {
10
seen.fetch_add(1, Ordering::SeqCst);
11
let amount: u64 = serde_json::from_slice(&input)?;
12
assert_eq!(amount, 4_000);
13
Ok(serde_json::to_vec("ch_test")?)
14
});
15
MockTaskBuilder::new("email_receipt".to_string(), mocks.clone()).returns(true);
16
17
let order = Order {
18
order_id: "ord_1".to_string(),
19
items: vec![1_500, 2_500],
20
};
21
let _: Receipt = TestWorkflowExecutor::new(mocks)
22
.execute_workflow(checkout, execution(), order)
23
.await?;
24
25
assert_eq!(calls.load(Ordering::SeqCst), 1);
26
Ok(())
27
}

A failing mock ends the test run with an error; the workflow doesn't receive it as a TaskFailed:

1
#[tokio::test]
2
async fn a_failing_mock_fails_the_run() {
3
let mocks = Arc::new(RwLock::new(MockRegistry::new()));
4
MockTaskBuilder::new("charge_card".to_string(), mocks.clone()).fails_with("declined");
5
6
let order = Order {
7
order_id: "ord_1".to_string(),
8
items: vec![100],
9
};
10
let outcome: Result<Receipt> = TestWorkflowExecutor::new(mocks)
11
.execute_workflow(checkout, execution(), order)
12
.await;
13
14
// The error ends the test run itself; the workflow never sees it.
15
assert!(outcome.is_err());
16
}

Workflows Without Tasks

TestEnv registers workflows by type name and runs them in memory. It does not consult task mocks, so use it for workflows whose steps are inline (ctx.execute) and use TestWorkflowExecutor for workflows that call tasks.

1
#[workflow]
2
pub async fn greet(ctx: WorkflowContext, name: String) -> Result<String> {
3
// An inline step runs during the test; there is no task to mock.
4
ctx.execute("format", move || async move { Ok(format!("Hello, {name}!")) })
5
.await
6
}
1
#[tokio::test]
2
async fn greets_by_name() -> Result<()> {
3
use orcher_sdk::testing::TestEnv;
4
5
let mut env = TestEnv::new();
6
env.register_workflow_with_context("greet", greet);
7
8
let greeting: String = env.execute_workflow("greet", "Ada").await?;
9
assert_eq!(greeting, "Hello, Ada!");
10
Ok(())
11
}

Testing Task Logic

There is no public constructor for TaskContext, so a #[task] body can't be called outside a worker. Keep the logic a task needs in plain functions and test those directly:

1
#[test]
2
fn totals_the_items() {
3
assert_eq!(total_cents(&[1_500, 2_500]), 4_000);
4
}

Actors

create_test_context(actor_name, key) builds an ActorContext backed by in-memory state, and #[operations] keeps each operation's body as <name>_impl:

1
mod actors {
2
use orcher_sdk::actor::testing::create_test_context;
3
use orcher_sdk::prelude::*;
4
5
#[actor]
6
pub struct Counter;
7
8
#[operations]
9
impl Counter {
10
#[operation(exclusive)]
11
pub async fn add(ctx: ActorContext, delta: i64) -> Result<i64> {
12
let count = ctx.state().get::<i64>("count").await?.unwrap_or(0) + delta;
13
ctx.state().set("count", &count).await?;
14
Ok(count)
15
}
16
}
17
18
#[tokio::test]
19
async fn adds_up() -> Result<()> {
20
// In-memory state, no server.
21
let ctx = create_test_context("Counter", "counter-1").await;
22
// `#[operations]` keeps each body as `<name>_impl`.
23
assert_eq!(Counter::add_impl(ctx.clone(), 5).await?, 5);
24
assert_eq!(Counter::add_impl(ctx, 2).await?, 7);
25
Ok(())
26
}
27
}

Clones of a context share its state. create_test_context_with_shared_state shares one store between several contexts.


What the Test Kit Doesn't Cover

  • TestWorkflowExecutor resolves tasks only. A workflow that waits on a timer, an event or a child workflow stops with an error at that point.
  • A mocked task never fails into the workflow, so failure handling (WorkflowError::TaskFailed, compensation) isn't exercised.
  • Task code never runs, and nothing is persisted or replayed from a real journal.
  • TestEnv records whether each run completed, but not the tasks or state of a run. Its advance_time moves a MockClock for your own code; it doesn't fire ctx.sleep timers.

For the rest, run the workflow against a server: start the engine locally, run a worker in the test process or beside it, and drive it with a Client.


Next Steps