AI workflows are easy to demonstrate when everything works.
An agent receives a request, calls a tool, produces an answer, and the workflow completes successfully.
Production systems are different.
An external API can time out. An MCP tool can return an error. An AI model can produce an invalid response. A downstream service can become temporarily unavailable. A human approval step can be rejected. A retry can succeed on the second attempt but fail repeatedly under sustained load.
These scenarios are particularly important when using declarative workflows because orchestration logic is defined outside traditional application code.
Microsoft Agent Framework declarative workflows allow .NET developers to define workflow behavior using YAML rather than implementing every orchestration path directly in C#. The YAML definition is loaded into a standard Workflow, which can then be executed and composed with code-based workflows. Declarative workflows support actions for control flow, agent and tool invocation, HTTP and MCP integration, and human-in-the-loop interactions.
That makes declarative workflows easier to review and modify, but it also creates a testing requirement:
How do you prove that the workflow behaves correctly when individual steps fail?
One effective answer is failure injection.
Instead of waiting for production failures, deliberately introduce controlled failures during testing and verify that the workflow follows the expected recovery path.
What Is Failure Injection?
Failure injection is a testing technique in which a controlled dependency failure is introduced to verify how an application behaves.
For an AI workflow, the dependency might be:
An AI agent
An MCP tool
An HTTP API
A database
A file or storage service
A human approval step
A downstream workflow
A checkpoint store
For example, consider:
User Request
|
v
Triage Agent
|
v
Customer API
|
v
Response Agent
A happy-path test verifies:
Triage → API → Response → Success
A failure-injection test might force:
Triage → API → Timeout
|
v
Retry
|
v
Success
Or:
Triage → API → Failure
|
v
Recovery Branch
|
v
User Message
The objective is not merely to verify that an exception is thrown.
The objective is to verify that the workflow reaches the correct state after the failure.
Why Declarative Workflows Need Failure Testing
Declarative workflows move orchestration logic into YAML.
A simplified workflow might look like:
kind: Workflow
trigger:
kind: OnConversationStart
id: support_workflow
actions:
- kind: InvokeAzureAgent
id: classify_request
agent:
name: TriageAgent
- kind: InvokeMcpTool
id: lookup_customer
tool:
name: get_customer
- kind: InvokeAzureAgent
id: generate_response
agent:
name: ResponseAgent
- kind: SendActivity
id: send_response
activity:
text: =Local.response
Microsoft's current declarative workflow documentation describes actions as the building blocks of a workflow, with actions executed according to the workflow definition. C# declarative workflows use a trigger-based YAML structure, and expressions can reference workflow state through namespaces such as Local.* and System.*.
The problem is that a visually correct YAML file does not prove that every failure path works.
A workflow can have excellent happy-path behavior and still fail badly when:
A tool times out.
An agent returns an unusable result.
A branch receives an unexpected value.
A retry executes incorrectly.
A checkpoint cannot be persisted.
A downstream dependency remains unavailable.
Define the Failure Contract First
Before injecting failures, define what the workflow is supposed to do.
For example:
| Failure | Expected Behavior |
|---|---|
| First API call fails | Retry |
| API remains unavailable | Return controlled error |
| Agent returns empty result | Branch to fallback |
| MCP tool fails | Do not continue with invalid data |
| Approval rejected | Stop privileged operation |
| Dependency timeout | Record failure and recover |
| Checkpoint failure | Surface workflow failure |
| Invalid input | Reject before expensive operations |
This becomes your test contract.
Without an expected outcome, failure injection only proves that something broke.
Build a Testable Workflow
A useful workflow should make important state observable.
For example:
kind: Workflow
trigger:
kind: OnConversationStart
id: customer_support
actions:
- kind: SetVariable
id: initialize
variable: Local.status
value: started
- kind: InvokeAzureAgent
id: classify_request
displayName: Classify customer request
agent:
name: TriageAgent
- kind: SetVariable
id: mark_classified
variable: Local.status
value: classified
- kind: SendActivity
id: send_status
activity:
text: =Concat("Workflow status: ", Local.status)
The exact agent configuration depends on the Agent Framework environment.
The important testing principle is that meaningful state transitions should be identifiable.
Instead of testing only:
Output == "Success"
test the workflow's intermediate behavior as well:
Started
↓
Classified
↓
Dependency Called
↓
Recovered
↓
Completed
Inject Failures at Dependency Boundaries
Do not randomly corrupt the entire workflow.
Inject failures at boundaries where external dependencies can realistically fail.
For example:
Workflow
|
+-- Agent
|
+-- MCP Tool ← Failure injection
|
+-- HTTP API ← Failure injection
|
+-- Database ← Failure injection
|
+-- Approval ← Failure injection
This makes failures deterministic and repeatable.
A good test should be able to say:
Given API failure on attempt 1,
when the workflow executes,
then it retries,
and the second attempt succeeds.
That is far more useful than a test that occasionally fails because a real external service happened to be unavailable.
Use a Failure-Injection Test Double
One practical pattern is to place a controllable wrapper around a dependency.
For example:
public interface ICustomerService
{
Task<Customer?> GetCustomerAsync(
string customerId,
CancellationToken cancellationToken);
}
The production implementation might call an HTTP service.
The test implementation can deliberately fail:
public sealed class FaultInjectingCustomerService
: ICustomerService
{
private readonly ICustomerService _inner;
private int _remainingFailures;
public FaultInjectingCustomerService(
ICustomerService inner,
int failuresBeforeSuccess)
{
_inner = inner;
_remainingFailures = failuresBeforeSuccess;
}
public Task<Customer?> GetCustomerAsync(
string customerId,
CancellationToken cancellationToken)
{
if (_remainingFailures > 0)
{
_remainingFailures--;
throw new HttpRequestException(
"Injected test failure.");
}
return _inner.GetCustomerAsync(
customerId,
cancellationToken);
}
}
Now a test can configure:
failuresBeforeSuccess = 1
and verify that the workflow's retry behavior works.
For persistent failure:
failuresBeforeSuccess = 100
can simulate a dependency that remains unavailable throughout the test.
The important characteristic is determinism.
Inject Timeouts Separately From Errors
A timeout is not identical to an HTTP 500 response.
A workflow may handle them differently.
A test double can deliberately delay a dependency:
public sealed class SlowCustomerService
: ICustomerService
{
public async Task<Customer?> GetCustomerAsync(
string customerId,
CancellationToken cancellationToken)
{
await Task.Delay(
TimeSpan.FromSeconds(30),
cancellationToken);
return null;
}
}
A test can then use a shorter timeout and verify that cancellation propagates correctly.
For example:
using var cts =
new CancellationTokenSource(
TimeSpan.FromSeconds(2));
await Assert.ThrowsAsync<OperationCanceledException>(
() => service.GetCustomerAsync(
"customer-123",
cts.Token));
The exact exception type should be verified against the application's HTTP/client implementation rather than assumed.
The important test is:
Dependency becomes slow
↓
Timeout occurs
↓
Workflow does not hang indefinitely
↓
Expected recovery path executes
Test Agent Failures Without Depending on a Real Model
AI model behavior is inherently variable.
A workflow test should not require a real LLM to produce exactly the same response every time.
Instead, separate orchestration tests from model-quality tests.
For orchestration testing, use a deterministic test agent or provider that can return predefined results.
For example:
public sealed class FakeAgent
{
private readonly string _response;
public FakeAgent(string response)
{
_response = response;
}
public Task<string> RunAsync(
string input,
CancellationToken cancellationToken)
{
return Task.FromResult(_response);
}
}
Tests can then simulate:
Valid response
Empty response
Malformed response
Expected refusal
Dependency error
Timeout
This allows the workflow itself to be tested independently of model variability.
Test Conditional Branches
Declarative workflows support conditional control flow. Microsoft documents actions such as If, ConditionGroup, Foreach, BreakLoop, ContinueLoop, and GotoAction for workflow control.
Suppose a workflow checks whether an agent produced a result:
- kind: If
id: validate_result
condition: =IsBlank(Local.AgentResult)
then:
- kind: SetVariable
id: mark_failure
variable: Local.status
value: failed
- kind: SendActivity
id: send_failure
activity:
text: "The request could not be completed."
else:
- kind: SetVariable
id: mark_success
variable: Local.status
value: completed
You should test both branches.
Test Case 1: Valid Result
AgentResult = valid
Expected status = completed
Test Case 2: Empty Result
AgentResult = empty
Expected status = failed
Test Case 3: Unexpected Result
AgentResult = malformed
Expected behavior = controlled failure
Testing only the first case leaves the most important workflow logic unverified.
Test Retry Behavior
Retries deserve dedicated tests.
Consider a dependency that fails twice and succeeds on the third attempt:
Attempt 1 → Failure
Attempt 2 → Failure
Attempt 3 → Success
The test should verify:
Number of calls = 3
Final workflow state = success
Then test permanent failure:
Attempt 1 → Failure
Attempt 2 → Failure
Attempt 3 → Failure
Expected:
Number of calls = configured retry limit
Final workflow state = controlled failure
Do not only assert that the final output is correct.
Also assert that the workflow did not exceed its retry policy.
Avoid Testing Retries With Real Delays
A common mistake is to make tests wait for actual retry delays.
For example:
Retry delay = 30 seconds
Retries = 5
could turn a unit test into a multi-minute test.
Use an injectable delay abstraction where appropriate:
public interface IRetryDelay
{
Task DelayAsync(
TimeSpan delay,
CancellationToken cancellationToken);
}
The production implementation performs the actual delay.
The test implementation can complete immediately.
This gives you deterministic tests without sacrificing production retry behavior.
Test MCP Tool Failures
If the workflow invokes MCP tools, treat the MCP server as an external dependency.
Test at least:
Tool succeeds
Tool returns expected error
Tool times out
Tool returns malformed data
Tool becomes unavailable
A useful test matrix is:
Join the conversation! Your thoughts help the community grow.