Temporal Workflow Testing with TestWorkflowEnvironment

Temporal Workflow Testing with TestWorkflowEnvironment

Temporal's TestWorkflowEnvironment is the cornerstone of reliable workflow testing. Unlike traditional unit tests where you mock out I/O and assert function return values, workflow tests need to simulate the passage of time, verify deterministic execution, test retry behavior, and validate that signals are handled correctly. This guide walks through everything you need to write comprehensive workflow tests in Go and Java.

Why Workflow Testing Is Different

Workflows in Temporal are long-running, stateful processes that can execute for hours, days, or even years. They coordinate activities—units of work that interact with the outside world—and must survive process crashes and restarts. This creates unique testing challenges:

  1. Time: A workflow that sleeps for 24 hours cannot be tested in real-time
  2. External dependencies: Activities call databases, APIs, and queues that shouldn't run during tests
  3. Non-determinism: Workflow code must be deterministic, but activities can be side-effectful
  4. Concurrency: Workflows handle signals, queries, and child workflows concurrently

TestWorkflowEnvironment solves all of these by providing a simulated Temporal server that runs entirely in-process, with controllable time and mock-able activities.

Setting Up the Test Environment in Go

First, add the Temporal SDK testing package to your module:

go get go.temporal.io/sdk
go get go.temporal.io/sdk/testsuite

The basic test structure uses Go's testing package along with Temporal's test suite:

package workflow_test

import (
    "testing"
    "time"

    "github.com/stretchr/testify/mock"
    "github.com/stretchr/testify/suite"
    "go.temporal.io/sdk/activity"
    "go.temporal.io/sdk/testsuite"
    "go.temporal.io/sdk/workflow"
)

type WorkflowTestSuite struct {
    suite.Suite
    testsuite.WorkflowTestSuite
    env *testsuite.TestWorkflowEnvironment
}

func (s *WorkflowTestSuite) SetupTest() {
    s.env = s.NewTestWorkflowEnvironment()
}

func (s *WorkflowTestSuite) AfterTest(suiteName, testName string) {
    s.env.AssertExpectations(s.T())
}

func TestWorkflowTestSuite(t *testing.T) {
    suite.Run(t, new(WorkflowTestSuite))
}

The WorkflowTestSuite embeds both testify's suite.Suite and Temporal's WorkflowTestSuite. The SetupTest method creates a fresh environment before each test, ensuring isolation. AfterTest verifies that all mock expectations were met.

Registering Workflows and Activities

Before you can execute a workflow in the test environment, you must register it—just like you would with a real worker:

// Define a simple order processing workflow
func OrderProcessingWorkflow(ctx workflow.Context, orderID string) (string, error) {
    ao := workflow.ActivityOptions{
        StartToCloseTimeout: 10 * time.Second,
    }
    ctx = workflow.WithActivityOptions(ctx, ao)

    var inventoryResult string
    err := workflow.ExecuteActivity(ctx, CheckInventoryActivity, orderID).Get(ctx, &inventoryResult)
    if err != nil {
        return "", fmt.Errorf("inventory check failed: %w", err)
    }

    var chargeResult string
    err = workflow.ExecuteActivity(ctx, ChargePaymentActivity, orderID).Get(ctx, &chargeResult)
    if err != nil {
        return "", fmt.Errorf("payment failed: %w", err)
    }

    var fulfillResult string
    err = workflow.ExecuteActivity(ctx, FulfillOrderActivity, orderID).Get(ctx, &fulfillResult)
    if err != nil {
        return "", fmt.Errorf("fulfillment failed: %w", err)
    }

    return fmt.Sprintf("Order %s processed: %s", orderID, fulfillResult), nil
}

func (s *WorkflowTestSuite) TestOrderProcessingWorkflow() {
    // Register workflow and activities
    s.env.RegisterWorkflow(OrderProcessingWorkflow)
    s.env.RegisterActivity(CheckInventoryActivity)
    s.env.RegisterActivity(ChargePaymentActivity)
    s.env.RegisterActivity(FulfillOrderActivity)

    // Mock activities
    s.env.OnActivity(CheckInventoryActivity, mock.Anything, "order-123").
        Return("in-stock", nil)
    s.env.OnActivity(ChargePaymentActivity, mock.Anything, "order-123").
        Return("charged-$99", nil)
    s.env.OnActivity(FulfillOrderActivity, mock.Anything, "order-123").
        Return("shipped-via-fedex", nil)

    // Execute workflow
    s.env.ExecuteWorkflow(OrderProcessingWorkflow, "order-123")

    // Assert completion
    s.True(s.env.IsWorkflowCompleted())
    s.NoError(s.env.GetWorkflowError())

    var result string
    s.NoError(s.env.GetWorkflowResult(&result))
    s.Contains(result, "order-123")
    s.Contains(result, "shipped-via-fedex")
}

The OnActivity method sets up mock expectations. The first argument to mock.Anything matches the activity context, and subsequent arguments match the actual parameters you expect the workflow to pass.

Mocking Activities with Specific Behavior

Simple return values are just the beginning. You can mock activities to simulate complex behaviors:

func (s *WorkflowTestSuite) TestPaymentFailureRetry() {
    s.env.RegisterWorkflow(OrderProcessingWorkflow)
    s.env.RegisterActivity(CheckInventoryActivity)
    s.env.RegisterActivity(ChargePaymentActivity)
    s.env.RegisterActivity(FulfillOrderActivity)

    callCount := 0

    s.env.OnActivity(CheckInventoryActivity, mock.Anything, "order-456").
        Return("in-stock", nil)

    // Fail twice, succeed on third attempt
    s.env.OnActivity(ChargePaymentActivity, mock.Anything, "order-456").
        Return("", temporal.NewApplicationError("payment gateway timeout", "TIMEOUT")).
        Once()
    s.env.OnActivity(ChargePaymentActivity, mock.Anything, "order-456").
        Return("", temporal.NewApplicationError("payment gateway timeout", "TIMEOUT")).
        Once()
    s.env.OnActivity(ChargePaymentActivity, mock.Anything, "order-456").
        Return("charged-$99", nil).
        Once()

    s.env.OnActivity(FulfillOrderActivity, mock.Anything, "order-456").
        Return("shipped", nil)

    _ = callCount

    s.env.ExecuteWorkflow(OrderProcessingWorkflow, "order-456")
    s.True(s.env.IsWorkflowCompleted())
    s.NoError(s.env.GetWorkflowError())
}

You can also use a function as the mock implementation for full control:

s.env.OnActivity(ChargePaymentActivity, mock.Anything, mock.Anything).
    Return(func(ctx context.Context, orderID string) (string, error) {
        if orderID == "fraud-order" {
            return "", temporal.NewApplicationError("fraud detected", "FRAUD")
        }
        return "charged", nil
    })

Testing Retry Policies

Temporal's retry policies are a critical part of workflow reliability. Here's how to test that your workflow correctly handles activity failures and retries:

func RetryableWorkflow(ctx workflow.Context, taskID string) error {
    retryPolicy := &temporal.RetryPolicy{
        InitialInterval:    time.Second,
        BackoffCoefficient: 2.0,
        MaximumInterval:    100 * time.Second,
        MaximumAttempts:    3,
    }

    ao := workflow.ActivityOptions{
        StartToCloseTimeout: 10 * time.Second,
        RetryPolicy:         retryPolicy,
    }
    ctx = workflow.WithActivityOptions(ctx, ao)

    return workflow.ExecuteActivity(ctx, UnreliableActivity, taskID).Get(ctx, nil)
}

func (s *WorkflowTestSuite) TestRetryPolicyExhausted() {
    s.env.RegisterWorkflow(RetryableWorkflow)
    s.env.RegisterActivity(UnreliableActivity)

    // Activity always fails
    s.env.OnActivity(UnreliableActivity, mock.Anything, "task-1").
        Return(temporal.NewApplicationError("service unavailable", "UNAVAILABLE")).
        Times(3) // Expect exactly 3 attempts (MaximumAttempts: 3)

    s.env.ExecuteWorkflow(RetryableWorkflow, "task-1")

    s.True(s.env.IsWorkflowCompleted())
    err := s.env.GetWorkflowError()
    s.Error(err)

    var appErr *temporal.ApplicationError
    s.True(errors.As(err, &appErr))
    s.Equal("UNAVAILABLE", appErr.Type())
}

func (s *WorkflowTestSuite) TestRetryPolicySucceedsOnThirdAttempt() {
    s.env.RegisterWorkflow(RetryableWorkflow)
    s.env.RegisterActivity(UnreliableActivity)

    s.env.OnActivity(UnreliableActivity, mock.Anything, "task-2").
        Return(temporal.NewApplicationError("transient error", "TRANSIENT")).
        Twice()
    s.env.OnActivity(UnreliableActivity, mock.Anything, "task-2").
        Return(nil).
        Once()

    s.env.ExecuteWorkflow(RetryableWorkflow, "task-2")

    s.True(s.env.IsWorkflowCompleted())
    s.NoError(s.env.GetWorkflowError())
}

Note that in the test environment, time advances automatically as activities complete (or fail). You don't need to wait real seconds for backoff intervals—the simulated clock handles it.

Signal Handling in Tests

Signals allow external systems to communicate with running workflows. Testing signal handling requires sending signals at the right point in workflow execution:

func ApprovalWorkflow(ctx workflow.Context, requestID string) (string, error) {
    ao := workflow.ActivityOptions{
        StartToCloseTimeout: 10 * time.Second,
    }
    ctx = workflow.WithActivityOptions(ctx, ao)

    // Submit the request
    err := workflow.ExecuteActivity(ctx, SubmitRequestActivity, requestID).Get(ctx, nil)
    if err != nil {
        return "", err
    }

    // Wait for approval signal
    approvalCh := workflow.GetSignalChannel(ctx, "approval-signal")

    var approved bool
    approvalCh.Receive(ctx, &approved)

    if !approved {
        return "rejected", nil
    }

    // Process approved request
    var result string
    err = workflow.ExecuteActivity(ctx, ProcessApprovedRequestActivity, requestID).Get(ctx, &result)
    if err != nil {
        return "", err
    }

    return result, nil
}

func (s *WorkflowTestSuite) TestApprovalWorkflowApproved() {
    s.env.RegisterWorkflow(ApprovalWorkflow)
    s.env.RegisterActivity(SubmitRequestActivity)
    s.env.RegisterActivity(ProcessApprovedRequestActivity)

    s.env.OnActivity(SubmitRequestActivity, mock.Anything, "req-789").
        Return(nil)
    s.env.OnActivity(ProcessApprovedRequestActivity, mock.Anything, "req-789").
        Return("request processed successfully", nil)

    // Send signal after SubmitRequestActivity completes
    s.env.RegisterDelayedCallback(func() {
        s.env.SignalWorkflow("approval-signal", true)
    }, 0) // 0 duration means "at the next available point"

    s.env.ExecuteWorkflow(ApprovalWorkflow, "req-789")

    s.True(s.env.IsWorkflowCompleted())
    s.NoError(s.env.GetWorkflowError())

    var result string
    s.NoError(s.env.GetWorkflowResult(&result))
    s.Equal("request processed successfully", result)
}

func (s *WorkflowTestSuite) TestApprovalWorkflowRejected() {
    s.env.RegisterWorkflow(ApprovalWorkflow)
    s.env.RegisterActivity(SubmitRequestActivity)

    s.env.OnActivity(SubmitRequestActivity, mock.Anything, "req-999").
        Return(nil)

    s.env.RegisterDelayedCallback(func() {
        s.env.SignalWorkflow("approval-signal", false)
    }, 0)

    s.env.ExecuteWorkflow(ApprovalWorkflow, "req-999")

    s.True(s.env.IsWorkflowCompleted())
    s.NoError(s.env.GetWorkflowError())

    var result string
    s.NoError(s.env.GetWorkflowResult(&result))
    s.Equal("rejected", result)
}

Testing Workflow Queries

Queries allow you to inspect workflow state without modifying it. Testing queries requires checking state at a specific point during execution:

func StatefulWorkflow(ctx workflow.Context) error {
    status := "initializing"

    // Register query handler
    err := workflow.SetQueryHandler(ctx, "get-status", func() (string, error) {
        return status, nil
    })
    if err != nil {
        return err
    }

    ao := workflow.ActivityOptions{StartToCloseTimeout: 10 * time.Second}
    ctx = workflow.WithActivityOptions(ctx, ao)

    status = "processing"
    err = workflow.ExecuteActivity(ctx, LongRunningActivity).Get(ctx, nil)
    if err != nil {
        status = "failed"
        return err
    }

    status = "completed"
    return nil
}

func (s *WorkflowTestSuite) TestWorkflowQueryDuringExecution() {
    s.env.RegisterWorkflow(StatefulWorkflow)
    s.env.RegisterActivity(LongRunningActivity)

    s.env.OnActivity(LongRunningActivity, mock.Anything).
        Return(nil).
        After(100 * time.Millisecond) // Simulate delay

    var queriedStatus string
    s.env.RegisterDelayedCallback(func() {
        // Query workflow state while it's processing
        val, err := s.env.QueryWorkflow("get-status")
        s.NoError(err)
        s.NoError(val.Get(&queriedStatus))
    }, 50*time.Millisecond)

    s.env.ExecuteWorkflow(StatefulWorkflow)

    s.True(s.env.IsWorkflowCompleted())
    s.NoError(s.env.GetWorkflowError())
    // The query during execution should have captured "processing"
    s.Equal("processing", queriedStatus)
}

Testing in Java with the Temporal Java SDK

The Java SDK provides similar test infrastructure through TestWorkflowEnvironment:

import io.temporal.client.WorkflowClient;
import io.temporal.client.WorkflowOptions;
import io.temporal.testing.TestWorkflowEnvironment;
import io.temporal.worker.Worker;
import org.junit.jupiter.api.*;
import org.mockito.Mockito;

import java.time.Duration;

class OrderWorkflowTest {
    private TestWorkflowEnvironment testEnv;
    private Worker worker;
    private WorkflowClient client;

    static final String TASK_QUEUE = "test-task-queue";

    @BeforeEach
    void setUp() {
        testEnv = TestWorkflowEnvironment.newInstance();
        worker = testEnv.newWorker(TASK_QUEUE);

        // Register workflow implementation
        worker.registerWorkflowImplementationTypes(OrderWorkflowImpl.class);

        client = testEnv.getWorkflowClient();
    }

    @AfterEach
    void tearDown() {
        testEnv.close();
    }

    @Test
    void testOrderWorkflowSuccess() {
        // Create mock activity
        OrderActivities mockActivities = Mockito.mock(OrderActivities.class);
        Mockito.when(mockActivities.checkInventory(Mockito.anyString()))
               .thenReturn("in-stock");
        Mockito.when(mockActivities.chargePayment(Mockito.anyString()))
               .thenReturn("charged");
        Mockito.when(mockActivities.fulfillOrder(Mockito.anyString()))
               .thenReturn("shipped");

        worker.registerActivitiesImplementations(mockActivities);
        testEnv.start();

        OrderWorkflow workflow = client.newWorkflowStub(
            OrderWorkflow.class,
            WorkflowOptions.newBuilder()
                .setTaskQueue(TASK_QUEUE)
                .setWorkflowExecutionTimeout(Duration.ofSeconds(30))
                .build()
        );

        String result = workflow.processOrder("order-123");

        Assertions.assertEquals("Order order-123 shipped", result);
        Mockito.verify(mockActivities).checkInventory("order-123");
        Mockito.verify(mockActivities).chargePayment("order-123");
        Mockito.verify(mockActivities).fulfillOrder("order-123");
    }

    @Test
    void testOrderWorkflowWithSignal() {
        ApprovalActivities mockActivities = Mockito.mock(ApprovalActivities.class);
        Mockito.when(mockActivities.submitForApproval(Mockito.anyString()))
               .thenReturn("submitted");
        Mockito.when(mockActivities.processApproved(Mockito.anyString()))
               .thenReturn("processed");

        worker.registerWorkflowImplementationTypes(ApprovalWorkflowImpl.class);
        worker.registerActivitiesImplementations(mockActivities);
        testEnv.start();

        ApprovalWorkflow workflow = client.newWorkflowStub(
            ApprovalWorkflow.class,
            WorkflowOptions.newBuilder()
                .setTaskQueue(TASK_QUEUE)
                .setWorkflowId("approval-test-1")
                .build()
        );

        // Start workflow asynchronously
        WorkflowClient.start(workflow::processRequest, "request-456");

        // Get stub to send signal
        ApprovalWorkflow workflowById = client.newWorkflowStub(
            ApprovalWorkflow.class, "approval-test-1"
        );

        // Send approval signal
        workflowById.approve(true);

        // Wait for and get result
        String result = WorkflowStub.fromTyped(workflow).getResult(String.class);
        Assertions.assertEquals("processed", result);
    }
}

Testing Child Workflows

Complex workflows often spawn child workflows. Here's how to test them:

func ParentWorkflow(ctx workflow.Context, batchID string, itemIDs []string) ([]string, error) {
    results := make([]string, 0, len(itemIDs))

    cwo := workflow.ChildWorkflowOptions{
        WorkflowExecutionTimeout: 30 * time.Minute,
    }

    var futures []workflow.Future
    for _, itemID := range itemIDs {
        childCtx := workflow.WithChildOptions(ctx, cwo)
        future := workflow.ExecuteChildWorkflow(childCtx, ItemWorkflow, itemID)
        futures = append(futures, future)
    }

    for _, future := range futures {
        var result string
        if err := future.Get(ctx, &result); err != nil {
            return nil, err
        }
        results = append(results, result)
    }

    return results, nil
}

func (s *WorkflowTestSuite) TestParentWorkflowWithChildren() {
    s.env.RegisterWorkflow(ParentWorkflow)
    s.env.RegisterWorkflow(ItemWorkflow)
    s.env.RegisterActivity(ProcessItemActivity)

    // Mock child workflow execution
    s.env.OnWorkflow(ItemWorkflow, mock.Anything, "item-1").
        Return("processed-item-1", nil)
    s.env.OnWorkflow(ItemWorkflow, mock.Anything, "item-2").
        Return("processed-item-2", nil)
    s.env.OnWorkflow(ItemWorkflow, mock.Anything, "item-3").
        Return("processed-item-3", nil)

    s.env.ExecuteWorkflow(ParentWorkflow, "batch-001", []string{"item-1", "item-2", "item-3"})

    s.True(s.env.IsWorkflowCompleted())
    s.NoError(s.env.GetWorkflowError())

    var results []string
    s.NoError(s.env.GetWorkflowResult(&results))
    s.Len(results, 3)
    s.Contains(results, "processed-item-1")
}

Asserting Workflow State After Completion

Beyond checking the return value, you often need to verify that side effects happened in the right order and with the right parameters:

func (s *WorkflowTestSuite) TestActivityCallOrder() {
    var callOrder []string
    mu := sync.Mutex{}

    s.env.OnActivity(CheckInventoryActivity, mock.Anything, mock.Anything).
        Return(func(ctx context.Context, orderID string) (string, error) {
            mu.Lock()
            callOrder = append(callOrder, "inventory")
            mu.Unlock()
            return "in-stock", nil
        })

    s.env.OnActivity(ChargePaymentActivity, mock.Anything, mock.Anything).
        Return(func(ctx context.Context, orderID string) (string, error) {
            mu.Lock()
            callOrder = append(callOrder, "payment")
            mu.Unlock()
            return "charged", nil
        })

    s.env.OnActivity(FulfillOrderActivity, mock.Anything, mock.Anything).
        Return(func(ctx context.Context, orderID string) (string, error) {
            mu.Lock()
            callOrder = append(callOrder, "fulfillment")
            mu.Unlock()
            return "shipped", nil
        })

    s.env.RegisterWorkflow(OrderProcessingWorkflow)
    s.env.RegisterActivity(CheckInventoryActivity)
    s.env.RegisterActivity(ChargePaymentActivity)
    s.env.RegisterActivity(FulfillOrderActivity)

    s.env.ExecuteWorkflow(OrderProcessingWorkflow, "order-789")

    s.True(s.env.IsWorkflowCompleted())
    s.NoError(s.env.GetWorkflowError())
    s.Equal([]string{"inventory", "payment", "fulfillment"}, callOrder)
}

Best Practices and Common Pitfalls

Always call AfterTest with AssertExpectations: If you set up a mock with Once() but the workflow never calls it, the test should fail. Without AssertExpectations, silent under-calling goes undetected.

Register before executing: Attempting to execute a workflow or activity that isn't registered results in a panic. Always register everything your workflow transitively uses.

Be careful with mock.Anything: It matches any value. Prefer specific matchers when possible to catch bugs where wrong arguments are passed.

Test failure paths explicitly: Don't just test the happy path. Write dedicated tests for each error case: activity timeouts, application errors, non-retryable errors, and workflow cancellation.

Use RegisterDelayedCallback sparingly: It's powerful but can make tests fragile if timing is off. Prefer designing workflows so they can be signaled to proceed rather than relying on time-based callbacks.

Isolate workflow logic from activity logic: Workflows should orchestrate; activities should execute. This separation makes both easier to test independently.

The TestWorkflowEnvironment gives you a complete, in-process Temporal server that makes workflow testing fast, reliable, and deterministic. Master it, and you'll be able to test even the most complex workflows with confidence.

Start now free