Bundle: redb-route / redb.Route.TestKit (redb.Route.TestKit.txt), 11 files
Snapshot: development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt
====
Path: redb-route/redb.Route.TestKit/AdviceWithBuilder.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.TestKit/AdviceWithBuilder.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Definitions;
namespace redb.Route.TestKit;
///
/// Rewrites one route definition before the context starts (Apache Camel AdviceWith):
/// swap the consumer, send matching To steps to mocks, or weave steps in, out and around
/// existing ones. The route under test is not modified for testability — the advice is.
/// Obtained through .
///
public sealed class AdviceWithBuilder
{
private readonly RouteDefinition _route;
internal AdviceWithBuilder(RouteDefinition route)
{
_route = route ?? throw new ArgumentNullException(nameof(route));
}
/// The route id being advised (explicit RouteId or the endpoint-derived fallback).
public string RouteId { get; internal init; } = string.Empty;
/// Replaces the route's From endpoint (Camel replaceFromWith): kafka://orders becomes direct://test-in.
public AdviceWithBuilder ReplaceFrom(string uri)
{
ArgumentException.ThrowIfNullOrWhiteSpace(uri);
_route.From(uri);
return this;
}
///
/// Sends every static To whose URI matches one of to the mock
/// standing in for it () instead of the original endpoint — the
/// original is never called. Masks: exact URI, scheme://prefix*, regex:....
///
public AdviceWithBuilder MockEndpoints(params string[] uriMasks)
{
if (uriMasks is not { Length: > 0 })
throw new ArgumentException("At least one URI mask is required.", nameof(uriMasks));
foreach (var slot in DefinitionTree.Slots(_route))
{
if (slot.Node is not ToDefinition to || !uriMasks.Any(mask => UriMask.IsMatch(mask, to.Uri)))
continue;
var mock = new ToDefinition(MockUri.For(to.Uri)) { StepId = to.StepId, Parent = slot.Owner };
slot.Owner.Outputs[slot.Index] = mock;
}
return this;
}
/// Same as ; the Camel name for "mock and do not call the original", kept for recognisability.
public AdviceWithBuilder MockEndpointsAndSkip(params string[] uriMasks) => MockEndpoints(uriMasks);
/// Selects the steps named via the Id("...") DSL verb.
public WeaveTarget WeaveById(string id)
{
ArgumentException.ThrowIfNullOrWhiteSpace(id);
return Select($"id '{id}'", s => s.Node is ProcessorDefinition { StepId: { } stepId } && string.Equals(stepId, id, StringComparison.OrdinalIgnoreCase));
}
/// Selects the static To steps whose URI matches .
public WeaveTarget WeaveByToUri(string uriMask)
{
ArgumentException.ThrowIfNullOrWhiteSpace(uriMask);
return Select($"To URI mask '{uriMask}'", s => s.Node is ToDefinition to && UriMask.IsMatch(uriMask, to.Uri));
}
/// Selects every step of definition type (e.g. ThrottleDefinition).
public WeaveTarget WeaveByType() where T : IProcessorDefinition
=> Select($"type {typeof(T).Name}", s => s.Node is T);
/// Adds the steps built by at the very beginning of the route.
public AdviceWithBuilder WeaveAddFirst(Action steps)
{
ArgumentNullException.ThrowIfNull(steps);
DefinitionTree.InsertAll(_route, 0, WeaveTarget.Build(steps));
return this;
}
/// Adds the steps built by at the very end of the route.
public AdviceWithBuilder WeaveAddLast(Action steps)
{
ArgumentNullException.ThrowIfNull(steps);
DefinitionTree.InsertAll(_route, _route.Outputs.Count, WeaveTarget.Build(steps));
return this;
}
private WeaveTarget Select(string what, Func match)
{
var slots = DefinitionTree.Slots(_route).Where(match).ToArray();
if (slots.Length == 0)
throw new InvalidOperationException($"AdviceWith on route '{RouteId}': no step matches {what}.");
return new WeaveTarget(this, slots);
}
}
Path: redb-route/redb.Route.TestKit/DefinitionTree.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.TestKit/DefinitionTree.cs
----
using redb.Route.Abstractions;
namespace redb.Route.TestKit;
///
/// A replaceable position in a route definition tree: is
/// Owner.Outputs[Index]. Branch containers reached through
/// (a When, a Catch) are walked for their
/// own outputs but are not slots themselves — a branch is structure, not a step.
///
internal readonly record struct DefinitionSlot(IProcessorDefinition Owner, int Index, IProcessorDefinition Node);
///
/// The one tree walk the test kit uses: the same shape as the core validator — recurse into
/// and into —
/// so MockEndpoints reaches a To inside Choice, Split, Multicast,
/// TryCatch, CircuitBreaker fallbacks and every other scope without per-type code.
///
internal static class DefinitionTree
{
/// All slots under , depth-first in document order (snapshot: safe to mutate while iterating).
public static List Slots(IProcessorDefinition root)
{
var slots = new List();
Collect(root, slots);
return slots;
}
private static void Collect(IProcessorDefinition owner, List slots)
{
for (var i = 0; i < owner.Outputs.Count; i++)
{
var child = owner.Outputs[i];
slots.Add(new DefinitionSlot(owner, i, child));
Collect(child, slots);
}
if (owner is IBranchingDefinition branching)
foreach (var branch in branching.Branches)
Collect(branch, slots);
}
/// Replaces owner.Outputs[index] with (zero or more nodes), re-parenting them.
public static void Splice(IProcessorDefinition owner, int index, IReadOnlyList replacements)
{
owner.Outputs.RemoveAt(index);
InsertAll(owner, index, replacements);
}
/// Inserts into owner.Outputs at , re-parenting them.
public static void InsertAll(IProcessorDefinition owner, int index, IReadOnlyList nodes)
{
for (var i = 0; i < nodes.Count; i++)
{
nodes[i].Parent = owner;
owner.Outputs.Insert(index + i, nodes[i]);
}
}
}
Path: redb-route/redb.Route.TestKit/MockUri.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.TestKit/MockUri.cs
----
namespace redb.Route.TestKit;
///
/// Maps an endpoint URI to the mock:// URI that stands in for it under
/// , the same way Apache Camel names its mocks
/// (mock:kafka:orders): the query string is dropped and scheme://path collapses to
/// scheme:path, so kafka://orders-vip?acks=all becomes mock://kafka:orders-vip.
///
public static class MockUri
{
/// Returns the mock:// URI standing in for ; a mock:// URI is returned unchanged.
public static string For(string endpointUri)
{
ArgumentException.ThrowIfNullOrWhiteSpace(endpointUri);
if (endpointUri.StartsWith("mock://", StringComparison.OrdinalIgnoreCase) ||
endpointUri.StartsWith("mock:", StringComparison.OrdinalIgnoreCase) && !endpointUri.Contains("://", StringComparison.Ordinal))
return endpointUri;
var queryIndex = endpointUri.IndexOf('?');
var withoutQuery = queryIndex >= 0 ? endpointUri[..queryIndex] : endpointUri;
return "mock://" + withoutQuery.Replace("://", ":", StringComparison.Ordinal);
}
}
Path: redb-route/redb.Route.TestKit/NotifyBuilder.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.TestKit/NotifyBuilder.cs
----
using redb.Route.Abstractions;
using redb.Route.Predicates;
namespace redb.Route.TestKit;
///
/// Builds a that waits for route events instead of a mock at the end of
/// the route (Apache Camel NotifyBuilder): "route orders has processed 3 exchanges
/// without failure" is ctx.Notify().FromRoute("orders").WhenDone(3).Create().
///
/// Scope (, , ) narrows which exchanges
/// are counted; the When* conditions are cumulative — the matcher matches when all of them hold.
///
///
public sealed class NotifyBuilder
{
private readonly IRouteContext _context;
private readonly List _routeIds = [];
private readonly List _fromMasks = [];
private readonly List>> _filters = [];
private int? _received, _completed, _failed, _done;
internal NotifyBuilder(IRouteContext context)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
}
/// Counts only exchanges of the route with this id (repeatable).
public NotifyBuilder FromRoute(string routeId)
{
ArgumentException.ThrowIfNullOrWhiteSpace(routeId);
_routeIds.Add(routeId);
return this;
}
/// Counts only exchanges of routes whose From URI matches the mask (kafka://*, regex:...).
public NotifyBuilder From(string uriMask)
{
ArgumentException.ThrowIfNullOrWhiteSpace(uriMask);
_fromMasks.Add(uriMask);
return this;
}
/// Counts only exchanges for which holds.
public NotifyBuilder Filter(Func predicate)
{
ArgumentNullException.ThrowIfNull(predicate);
_filters.Add(e => Task.FromResult(predicate(e)));
return this;
}
/// Counts only exchanges for which holds (awaited).
public NotifyBuilder Filter(IPredicate predicate)
{
ArgumentNullException.ThrowIfNull(predicate);
_filters.Add(predicate.MatchesAsync);
return this;
}
/// Counts only exchanges for which the route-language condition holds (same compiler as Filter(string) in routes).
public NotifyBuilder Filter(string condition)
{
ArgumentException.ThrowIfNullOrWhiteSpace(condition);
_filters.Add(PredicateFactory.FromString(condition).MatchesAsync);
return this;
}
/// Matches once at least exchanges have entered the scoped routes.
public NotifyBuilder WhenReceived(int count) { _received = Positive(count); return this; }
/// Matches once at least exchanges completed without a propagated exception.
public NotifyBuilder WhenCompleted(int count) { _completed = Positive(count); return this; }
/// Matches once at least exchanges escaped their route with an exception.
public NotifyBuilder WhenFailed(int count) { _failed = Positive(count); return this; }
/// Matches once at least exchanges finished, completed or failed.
public NotifyBuilder WhenDone(int count) { _done = Positive(count); return this; }
/// Registers the matcher as a lifecycle listener on the context and starts counting.
public NotifyMatcher Create()
{
if (_received is null && _completed is null && _failed is null && _done is null)
throw new InvalidOperationException("NotifyBuilder needs at least one When* condition (WhenReceived / WhenCompleted / WhenFailed / WhenDone).");
var matcher = new NotifyMatcher(_context, _routeIds.ToArray(), _fromMasks.ToArray(), _filters.ToArray(),
_received, _completed, _failed, _done);
_context.AddLifecycleListener(matcher);
return matcher;
}
private static int Positive(int count) => count >= 1 ? count : throw new ArgumentOutOfRangeException(nameof(count), "Counts start at 1.");
}
Path: redb-route/redb.Route.TestKit/NotifyMatcher.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.TestKit/NotifyMatcher.cs
----
using System.Diagnostics;
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.TestKit;
///
/// Counts exchange events (received / completed / failed) for the scope chosen in
/// and reports when the configured conditions hold.
/// Registered as an ; events arrive from the route's outermost
/// wrapper, so "completed" and "failed" reflect the final outcome after error handling.
///
public sealed class NotifyMatcher : IRouteLifecycleListener, IDisposable
{
private readonly IRouteContext _context;
private readonly string[] _routeIds;
private readonly string[] _fromMasks;
private readonly Func>[] _filters;
private readonly int? _received, _completed, _failed, _done;
private int _receivedCount, _completedCount, _failedCount;
private TaskCompletionSource _changed = NewSignal();
private volatile bool _disposed;
internal NotifyMatcher(IRouteContext context, string[] routeIds, string[] fromMasks, Func>[] filters,
int? received, int? completed, int? failed, int? done)
{
_context = context;
_routeIds = routeIds;
_fromMasks = fromMasks;
_filters = filters;
_received = received;
_completed = completed;
_failed = failed;
_done = done;
}
/// Exchanges that entered the scoped routes.
public int ReceivedCount => Volatile.Read(ref _receivedCount);
/// Exchanges that completed without a propagated exception.
public int CompletedCount => Volatile.Read(ref _completedCount);
/// Exchanges that escaped their route with an exception.
public int FailedCount => Volatile.Read(ref _failedCount);
/// Completed plus failed.
public int DoneCount => CompletedCount + FailedCount;
/// true when every configured condition currently holds.
public bool Matches()
=> (_received is null || ReceivedCount >= _received)
&& (_completed is null || CompletedCount >= _completed)
&& (_failed is null || FailedCount >= _failed)
&& (_done is null || DoneCount >= _done);
/// Waits up to for the conditions to hold; false on timeout.
public async Task MatchesAsync(TimeSpan timeout, CancellationToken ct = default)
{
var clock = Stopwatch.StartNew();
while (true)
{
var signal = Volatile.Read(ref _changed).Task;
if (Matches()) return true;
var remaining = timeout - clock.Elapsed;
if (remaining <= TimeSpan.Zero) return false;
await Task.WhenAny(signal, Task.Delay(remaining, ct)).ConfigureAwait(false);
ct.ThrowIfCancellationRequested();
}
}
/// Zeroes the counters so the same matcher can be reused for the next batch.
public void Reset()
{
Interlocked.Exchange(ref _receivedCount, 0);
Interlocked.Exchange(ref _completedCount, 0);
Interlocked.Exchange(ref _failedCount, 0);
}
/// Stops counting. The listener registration stays with the context but ignores further events.
public void Dispose() => _disposed = true;
// ── IRouteLifecycleListener ──────────────────────────────────────────────
async Task IRouteLifecycleListener.OnExchangeReceived(string routeId, IExchange exchange, CancellationToken ct)
{
if (await InScope(routeId, exchange).ConfigureAwait(false))
Bump(ref _receivedCount);
}
async Task IRouteLifecycleListener.OnExchangeCompleted(string routeId, IExchange exchange, CancellationToken ct)
{
if (await InScope(routeId, exchange).ConfigureAwait(false))
Bump(ref _completedCount);
}
async Task IRouteLifecycleListener.OnExchangeFailed(string routeId, IExchange exchange, Exception exception, CancellationToken ct)
{
if (await InScope(routeId, exchange).ConfigureAwait(false))
Bump(ref _failedCount);
}
private async Task InScope(string routeId, IExchange exchange)
{
if (_disposed) return false;
if (_routeIds.Length > 0 && !_routeIds.Contains(routeId, StringComparer.OrdinalIgnoreCase))
return false;
if (_fromMasks.Length > 0)
{
var route = _context.Routes.FirstOrDefault(r => string.Equals(r.RouteId, routeId, StringComparison.OrdinalIgnoreCase));
if (route is null || !_fromMasks.Any(mask => UriMask.IsMatch(mask, route.FromUri)))
return false;
}
foreach (var filter in _filters)
if (!await filter(exchange).ConfigureAwait(false))
return false;
return true;
}
private void Bump(ref int counter)
{
Interlocked.Increment(ref counter);
Interlocked.Exchange(ref _changed, NewSignal()).TrySetResult(true);
}
private static TaskCompletionSource NewSignal() => new(TaskCreationOptions.RunContinuationsAsynchronously);
}
Path: redb-route/redb.Route.TestKit/README.md
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.TestKit/README.md
----
# redb.Route.TestKit
> Documentation and articles:
Test a route without its brokers, without changing the route. Works with xUnit, NUnit and MSTest:
assertions throw `MockAssertionException`, no test-framework dependency.
```csharp
await using var ctx = new RouteContext().AddRoutes(new OrdersRoutes());
ctx.AdviceRoute("orders", a => a
.ReplaceFrom("direct://test-in") // instead of kafka://orders
.MockEndpoints("kafka://*", "sql:*")); // every matching To(...) goes to a mock
await ctx.Start();
var vip = ctx.Mock("kafka://orders-vip");
vip.ExpectMessageCount(1).ExpectHeader("priority", "high");
await ctx.SendBody("direct://test-in", order);
await vip.AssertIsSatisfiedAsync(TimeSpan.FromSeconds(2));
```
## What is inside
| API | Purpose |
|---|---|
| `ctx.AdviceRoute(routeId, a => ...)` | rewrite a route definition before `Start()`: `ReplaceFrom`, `MockEndpoints`, `MockEndpointsAndSkip`, `WeaveById`, `WeaveByToUri`, `WeaveAddFirst`, `WeaveAddLast` |
| `ctx.Mock(uri)` | the `MockEndpoint` standing in for `uri` (original URI or `mock://name`) |
| `MockEndpoint.Expect*` | `ExpectMessageCount`, `ExpectMinimumMessageCount`, `ExpectBodies`, `ExpectBodiesInAnyOrder`, `ExpectHeader`, `ExpectHeaderReceived`, `ExpectProperty`, `Expect(predicate / condition string)` |
| `MockEndpoint.AssertIsSatisfiedAsync(timeout)` | waits, then fails with an "Expected / but was" diff and the bodies received |
| `MockEndpoint.Whenever(n) / WheneverAny()` | scripted replies: `SetBody`, `SetHeader`, `Delay`, `Throw`, `Do` — for `Enrich` and request-reply through `mock://` |
| `ctx.Notify().FromRoute("orders").WhenDone(3).Create()` | wait for route events (`WhenReceived`, `WhenCompleted`, `WhenFailed`, `WhenDone`, `From(uriMask)`, `Filter(condition)`) without a mock at the end |
| `ctx.SendBody`, `ctx.SendBodyAndHeaders`, `ctx.RequestBody` | one-line sends instead of endpoint/producer plumbing |
URI masks (`MockEndpoints`, `WeaveByToUri`, `Notify().From`): exact URI, prefix with a trailing `*`
(`kafka://*`), or `regex:`. Query strings are ignored for matching.
`MockEndpoints` rewrites the static `To(...)` steps of the advised route; a dynamic `ToD(...)`
resolves its URI per message and is not rewritten — point it at a `mock://` URI through the
message instead.
Path: redb-route/redb.Route.TestKit/RouteContextAdviceExtensions.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.TestKit/RouteContextAdviceExtensions.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Definitions;
namespace redb.Route.TestKit;
///
/// AdviceWith entry points. Advice runs in the window between
/// and : the builders are configured once, the chosen definitions are
/// rewritten in place, and Start() compiles them as rewritten (it does not re-run Configure()).
///
public static class RouteContextAdviceExtensions
{
///
/// Rewrites the route with id (an explicit RouteId("..."), or the
/// endpoint-derived id of an unnamed route) before the context starts.
///
/// The context is already started, or no route has that id.
public static RouteContext AdviceRoute(this RouteContext context, string routeId, Action advice)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentException.ThrowIfNullOrWhiteSpace(routeId);
ArgumentNullException.ThrowIfNull(advice);
var routes = BuiltRoutes(context);
var match = routes.FirstOrDefault(r => string.Equals(r.Id, routeId, StringComparison.OrdinalIgnoreCase));
if (match.Definition is null)
throw new InvalidOperationException(
$"AdviceWith: no route with id '{routeId}'. Known routes: {string.Join(", ", routes.Select(r => $"'{r.Id}'"))}.");
advice(new AdviceWithBuilder(match.Definition) { RouteId = match.Id });
return context;
}
/// Applies the same advice to every route of the context (e.g. a => a.MockEndpoints("kafka://*")).
public static RouteContext AdviceAllRoutes(this RouteContext context, Action advice)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(advice);
foreach (var (id, definition) in BuiltRoutes(context))
advice(new AdviceWithBuilder(definition) { RouteId = id });
return context;
}
/// Configures the builders once (idempotent) and lists their routes with resolved ids.
private static List<(string Id, RouteDefinition Definition)> BuiltRoutes(RouteContext context)
{
if (context.IsStarted)
throw new InvalidOperationException("AdviceWith must run before RouteContext.Start(): routes are compiled from their definitions at start.");
// Build every builder that has not been built yet (one added after an earlier advice included);
// a built one keeps its definitions, and with them any advice already applied.
foreach (var builder in context.RouteBuilders)
{
if (!builder.IsBuilt)
builder.InternalBuild(context);
}
context.DefinitionsPrebuilt = true;
var routes = new List<(string, RouteDefinition)>();
foreach (var builder in context.RouteBuilders)
{
foreach (var definition in builder.Definitions)
{
var fromUri = definition.GetFromUri()
?? throw new InvalidOperationException($"Route '{definition.GetRouteId() ?? "(unnamed)"}' has no From() endpoint.");
// Same fallback the context uses when compiling an unnamed route.
var id = definition.GetRouteId() ?? RouteIdFactory.ForEndpoint(EndpointUriParser.Parse(fromUri));
routes.Add((id, definition));
}
}
return routes;
}
}
Path: redb-route/redb.Route.TestKit/RouteContextNotifyExtensions.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.TestKit/RouteContextNotifyExtensions.cs
----
using redb.Route.Abstractions;
namespace redb.Route.TestKit;
/// Entry point for : ctx.Notify().FromRoute("orders").WhenDone(3).Create().
public static class RouteContextNotifyExtensions
{
/// Starts building a for this context.
public static NotifyBuilder Notify(this IRouteContext context) => new(context);
}
Path: redb-route/redb.Route.TestKit/RouteContextSendExtensions.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.TestKit/RouteContextSendExtensions.cs
----
using redb.Route.Abstractions;
using redb.Route.Components;
using redb.Route.Core;
namespace redb.Route.TestKit;
///
/// One-line sends for tests: replaces the GetEndpoint / CreateProducer / Start / Process
/// plumbing with , and ,
/// plus to reach the mock standing in for an endpoint.
/// Each call uses a short-lived , so producers are started and stopped
/// around the send and nothing leaks between tests.
///
public static class RouteContextSendExtensions
{
/// Sends to (in-only).
public static async Task SendBody(this IRouteContext context, string endpointUri, object? body, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(context);
using var template = Template(context);
var exchange = Exchange.Create(new Message(body), null);
try { await template.SendAsync(endpointUri, exchange, ct).ConfigureAwait(false); }
finally { await exchange.DisposeAsync().ConfigureAwait(false); }
}
/// Sends with the given headers to (in-only).
public static async Task SendBodyAndHeaders(this IRouteContext context, string endpointUri, object? body,
IEnumerable> headers, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(headers);
using var template = Template(context);
var exchange = Exchange.Create(WithHeaders(body, headers), null);
try { await template.SendAsync(endpointUri, exchange, ct).ConfigureAwait(false); }
finally { await exchange.DisposeAsync().ConfigureAwait(false); }
}
/// Sends with a single header to (in-only).
public static Task SendBodyAndHeader(this IRouteContext context, string endpointUri, object? body,
string headerName, object? headerValue, CancellationToken ct = default)
=> context.SendBodyAndHeaders(endpointUri, body, [new KeyValuePair(headerName, headerValue)], ct);
/// Request-reply: sends and returns the reply body converted to .
public static async Task RequestBody(this IRouteContext context, string endpointUri, object? body, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(context);
using var template = Template(context);
var exchange = Exchange.Create(new Message(body), null);
try
{
var reply = await template.RequestAsync(endpointUri, exchange, ct).ConfigureAwait(false);
return ReplyAs(reply, endpointUri);
}
finally { await exchange.DisposeAsync().ConfigureAwait(false); }
}
/// Request-reply with headers; returns the reply body converted to .
public static async Task RequestBodyAndHeaders(this IRouteContext context, string endpointUri, object? body,
IEnumerable> headers, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(headers);
using var template = Template(context);
var exchange = Exchange.Create(WithHeaders(body, headers), null);
try
{
var reply = await template.RequestAsync(endpointUri, exchange, ct).ConfigureAwait(false);
return ReplyAs(reply, endpointUri);
}
finally { await exchange.DisposeAsync().ConfigureAwait(false); }
}
///
/// The standing in for : either a mock://name
/// URI or the original endpoint URI that replaced
/// (kafka://orders-vip resolves to mock://kafka:orders-vip, see ).
/// The endpoint is created on first access, so expectations can be set before any message arrives.
///
public static MockEndpoint Mock(this IRouteContext context, string uri)
{
ArgumentNullException.ThrowIfNull(context);
var endpoint = context.GetEndpoint(MockUri.For(uri));
return endpoint as MockEndpoint
?? throw new InvalidOperationException($"'{uri}' resolved to '{endpoint.GetType().Name}', not a MockEndpoint.");
}
private static ProducerTemplate Template(IRouteContext context)
{
var template = new ProducerTemplate(context);
template.Start();
return template;
}
private static Message WithHeaders(object? body, IEnumerable> headers)
{
var message = new Message(body);
foreach (var (key, value) in headers)
message.Headers[key] = value;
return message;
}
///
/// The reply body converted to , taken before the helper ends the exchange. A body that reads
/// from resources of the exchange () would be dead once the helper returns, so it is
/// refused; a nullable converts to its underlying type.
///
private static T? ReplyAs(IExchange reply, string endpointUri)
{
var replyBody = reply.Out?.Body ?? reply.In.Body;
if (replyBody is IExchangeBoundBody)
throw new InvalidOperationException(
$"The reply of '{EndpointUri.Sanitize(endpointUri)}' is a {ReadableName(replyBody.GetType())} that reads from " +
"resources of its exchange, and the helper ends the exchange before it returns. Use " +
"ProducerTemplate.RequestAsync, read the body, then dispose the exchange.");
return replyBody switch
{
null => default,
T typed => typed,
_ => (T)RouteDecimal.ChangeType(replyBody, Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T),
System.Globalization.CultureInfo.InvariantCulture),
};
}
/// StreamedQueryResult<Order> rather than the runtime name StreamedQueryResult`1.
private static string ReadableName(Type type) =>
type.IsGenericType
? $"{type.Name[..type.Name.IndexOf('`')]}<{string.Join(", ", type.GetGenericArguments().Select(ReadableName))}>"
: type.Name;
}
Path: redb-route/redb.Route.TestKit/WeaveTarget.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.TestKit/WeaveTarget.cs
----
using redb.Route.Abstractions;
using redb.Route.Definitions;
namespace redb.Route.TestKit;
///
/// The steps selected by ,
/// or , ready to be replaced, wrapped or removed
/// (Apache Camel weaveById(...).replace() / .before() / .after() / .remove()).
/// New steps are written with the ordinary route DSL: t.Replace(r => r.To("mock://x")).
///
public sealed class WeaveTarget
{
private readonly AdviceWithBuilder _owner;
private readonly IReadOnlyList _slots;
internal WeaveTarget(AdviceWithBuilder owner, IReadOnlyList slots)
{
_owner = owner;
_slots = slots;
}
/// Number of steps selected.
public int Count => _slots.Count;
/// Replaces each selected step with the steps built by .
public AdviceWithBuilder Replace(Action steps)
{
ArgumentNullException.ThrowIfNull(steps);
foreach (var slot in Descending())
DefinitionTree.Splice(slot.Owner, slot.Index, Build(steps));
return _owner;
}
/// Inserts the steps built by before each selected step.
public AdviceWithBuilder Before(Action steps)
{
ArgumentNullException.ThrowIfNull(steps);
foreach (var slot in Descending())
DefinitionTree.InsertAll(slot.Owner, slot.Index, Build(steps));
return _owner;
}
/// Inserts the steps built by after each selected step.
public AdviceWithBuilder After(Action steps)
{
ArgumentNullException.ThrowIfNull(steps);
foreach (var slot in Descending())
DefinitionTree.InsertAll(slot.Owner, slot.Index + 1, Build(steps));
return _owner;
}
/// Removes each selected step.
public AdviceWithBuilder Remove()
{
foreach (var slot in Descending())
slot.Owner.Outputs.RemoveAt(slot.Index);
return _owner;
}
/// Builds steps on a scratch route so the full DSL is available, then hands over its outputs.
internal static IReadOnlyList Build(Action steps)
{
var scratch = new RouteDefinition();
steps(scratch);
return scratch.Outputs.ToArray();
}
// Mutate from the back of each owner list so earlier indices stay valid.
private IEnumerable Descending() => _slots.OrderByDescending(s => s.Index);
}
Path: redb-route/redb.Route.TestKit/redb.Route.TestKit.csproj
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.TestKit/redb.Route.TestKit.csproj
----
redb.Route.TestKit
Test kit for redb.Route: AdviceWith (ReplaceFrom, MockEndpoints, weaving), rich mock expectations, NotifyBuilder and send helpers. Test routes without brokers, with any test framework.
esb;messaging;testing;mock;advicewith;redb
README.md