Testing your jobs¶
Handlers are plain classes built by dependency injection, so most of them are tested like any class: construct one with fakes and call HandleAsync. To test what happens around them, enqueuing, scheduling, retries and recurring jobs, use the Bellhop.Testing package:
BellhopTestHarness is a Bellhop node with an in-memory store of its own and a fake clock, where nothing runs in the background: jobs run only when the test calls RunPendingAsync or AdvanceTimeAsync, one at a time and in a fixed order, and a retry waits exactly its configured delay. The same test runs the same jobs with the same outcomes every time, and two harnesses share no job, time or service, so tests run in parallel. One exception: a metrics listener on the Bellhop meter hears every harness in the process, so run tests that read metrics on their own.
[Fact]
public async Task RegisteringAUser_SendsTheWelcomeEmail_AndTheFollowUpThreeDaysLater()
{
var ct = TestContext.Current.CancellationToken;
var email = new RecordingEmailSender();
await using var harness = await BellhopTestHarness.StartAsync(
bellhop => bellhop
.AddJob<SendWelcomeEmail, SendWelcomeEmailHandler>()
.AddJob<SendFollowUpEmail, SendFollowUpEmailHandler>(),
services => services.AddSingleton<IEmailSender>(email),
ct: ct);
var userId = Guid.NewGuid();
await new RegisterUser(harness.Client).RegisterAsync(new User(userId));
await harness.RunPendingAsync(ct);
email.Welcomed.Should().Equal(userId);
harness.Jobs<SendFollowUpEmail>().Should().ContainSingle().Which.State.Should().Be(JobState.Scheduled);
await harness.AdvanceTimeAsync(TimeSpan.FromDays(3), ct);
harness.Jobs<SendFollowUpEmail>().Should().ContainSingle().Which.State.Should().Be(JobState.Succeeded);
}
Register the jobs and the test's fakes as in AddBellhop. Assert on what was enqueued with Enqueued<TJob>(), on the jobs and their states with Jobs<TJob>(), or on the harness's Store. A job that fails stays on its normal path, failed until its retry is due on the harness's clock, and its exception is in its history rather than thrown at the test.
UseInlineExecution() in the harness's configuration runs each job inside the enqueue call instead, for tests that want the job done the moment the code under test returns.
- What runs in the call.
EnqueueAsync,EnqueueManyAsync,ChainAsync,ContinueWithAsync,CreateBatchAsyncand the recurring manager'sTriggerAsyncrun every job they store enqueued, in the call's order. After each job ends, the jobs its outcome releases run too: its continuations, the next step of a chain, and the batch continuations its batch's last member releases. A continuation added to a finished parent runs in its own call when the parent's outcome released it.ScheduleAsynconly stores its job, and the other calls (cancel, requeue, delete) leave what they release toRunPendingAsync. - Failures. A job that throws is dead-lettered, never retried, so its
OnFailureandOnCompletioncontinuations run and itsOnSuccessones do not. The call finishes its other work first, then throws the first exception, in run order; the later ones are logged and stored with their dead-lettered jobs. A cancelled token stops the call before its next job withOperationCanceledException; what has not run stays enqueued. - Concurrency keys. A job whose concurrency key is held by as many running jobs as its Max is deferred rather than failed or blocked: its call returns without running it, and it runs on the call of the job holding the key, right after that job ends. So a handler that enqueues a job with its own key does not deadlock: the job runs once the handler has finished, before the outer call returns. A deferred job's exception reaches the holder's call. A job whose queue is also at its concurrency limit is not deferred: its call throws, as for any job enqueued into a full queue.
- Paused claims. A job no node may claim, as the maintenance pause is on or its queue is paused or at its concurrency limit, does not run: the call that stored it throws, and a job an outcome released or a concurrency key deferred stays enqueued for
RunPendingAsync. On a Redis store the same holds while the store reconciles after a reset, and until a worker node has initialised it, as a harness worker never writes the generation marker (see Running in production). - Rate limits. A job whose rate limit is reached is not run and stays enqueued;
AdvanceTimeAsyncorRunPendingAsyncruns it once its window allows. The LongRunning limit, a worker's option, does not apply. - Depth. A handler's own enqueue runs its job nested in the handler's run. A call nested 32 deep throws
InvalidOperationExceptionand leaves its jobs enqueued; a job that enqueues itself recursively should schedule the next run, and the test run it withRunPendingAsync.