Fakes
- Introduction
- Complete Example: Failed HTTP Response
- Queue Fake
- Event Fake
- Log Fake
- HTTP Fake
- Storage Fake
- Swapping Any Facade
- Not Yet Available
Introduction
When testing, you often want to know that your code queued a job, dispatched an event, or called an API, without actually doing it. Like Laravel's Queue::fake(), DotBlaze's facades can be swapped for fakes that record what happened and offer assertion methods. Each Fake() call returns the fake so you can assert on it:
var queue = Queue.Fake();
await new SendWelcomeEmail { User = user, Subject = "Hi" }.Dispatch().OnQueue("emails");
queue.AssertPushedOn<SendWelcomeEmail>("emails");Every failed assertion throws an InvalidOperationException describing what was expected, which fails the test.
Where Fakes Apply
Fakes are stored per async flow (AsyncLocal), not globally. That is what makes them safe for tests running in parallel: two tests can fake the same facade at the same time and each sees only its own records. It also sets the rules for using them:
- Call
Fake()in the test method itself, or inside theServiceScope.Runclosure that runs the code under test. A fake installed inside a separateasynchelper method disappears when that helper returns. - The fake applies to everything the test awaits afterwards, including models, jobs run inline, and listeners.
- With
TestApp, fakes also reach the requests the test sends, see Fakes and HTTP Tests. (A plainWebApplicationFactoryruns requests on their own flow; set its server'sPreserveExecutionContexttotrueto get the same.)
[Fact]
public async Task Registering_queues_the_welcome_email()
{
await ServiceScope.Run(app.Services, async () =>
{
var queue = Queue.Fake();
var user = await User.Create(new { Name = "Ali", Email = "fake@example.com", Password = "password123" });
await new SendWelcomeEmail { User = user, Subject = "Welcome!" }.Dispatch();
queue.AssertPushed<SendWelcomeEmail>(j => j.User.Id == user.Id);
});
}Queue Fake
Queue.Fake() records jobs instead of queueing them. Jobs are not serialized and never run. Jobs without IShouldQueue still run immediately, because they never reach the queue.
var queue = Queue.Fake();
// ... code that dispatches jobs ...
queue.AssertPushed<SendWelcomeEmail>();
queue.AssertPushed<SendWelcomeEmail>(j => j.User.Id == user.Id);
queue.AssertPushedOn<SendWelcomeEmail>("emails");
queue.AssertPushedOn<SendWelcomeEmail>("emails", j => j.Subject == "Hi");
queue.AssertNotPushed<ImportFeed>();
queue.AssertNothingPushed();For other checks, queue.All lists every pushed job as a PushedJob(Job, Queue, Delay), and queue.Pushed<TJob>() returns the pushed jobs of one type:
var pushed = Assert.Single(queue.All);
Assert.Equal(TimeSpan.FromMinutes(10), pushed.Delay);The queue name is null when the job was dispatched without OnQueue. Queued listeners appear as CallQueuedListener jobs.
Event Fake
Event.Fake() records events and runs no listeners. Model events are recorded too, so saving a model inside the test adds Saving<T>, Created<T>, and so on:
var events = Event.Fake();
var author = await Author.Create(new { Name = "A", Password = "x" });
author.Name = "B";
await author.Save();
await author.Delete();
events.AssertDispatched<Creating<Author>>();
events.AssertDispatched<Created<Author>>(e => e.Model.Id == author.Id);
events.AssertDispatched<Updated<Author>>(e => e.Model.Name == "B");
events.AssertDispatched<Deleted<Author>>();
events.AssertNotDispatched<OrderShipped>();AssertNothingDispatched() checks that no event was dispatched at all. events.All and events.Dispatched<TEvent>() give you the recorded events. Event.Listen does nothing while the fake is active.
Log Fake
Log.Fake() records messages written through the Log facade, with their channel, level, rendered message, and exception:
var log = Log.Fake();
Log.Info("User {Id} login", 7);
Log.Error(new InvalidOperationException("x"), "Failed to send invoice {Id}", 9);
Log.Channel("slack").Critical("Disk full");
log.AssertLogged(e => e is { Level: LogLevel.Information, Message: "User 7 login", Channel: Log.DefaultChannel });
log.AssertLogged(e => e.Level == LogLevel.Error && e.Exception is InvalidOperationException);
log.AssertLogged(e => e is { Channel: "slack", Level: LogLevel.Critical });AssertNothingLogged() checks that nothing was logged, and log.Entries lists every LogEntry. Only the Log facade is faked: messages written through an injected ILogger<T>, including the framework's own, are not recorded. Log.Fake() works without an active service scope.
HTTP Fake
Http.Fake() stops the HTTP client from sending real requests. Pass stub responses keyed by URL pattern, where * matches anything; the pattern is matched against the host and path, or against the full URL. Requests that match no pattern get an empty 200 response:
Http.Fake(new()
{
["api.example.com/users*"] = Http.Response(new[] { new { id = 1, name = "Ali" } }, 200, new { X_Total = "1" }),
["api.example.com/broken"] = Http.Response("oops", 500),
});
var res = await Http.WithToken("t0k3n").Get("https://api.example.com/users", new { page = 2 });
Http.AssertSent(r => r.Url == "https://api.example.com/users?page=2" && r.Headers["Authorization"] == "Bearer t0k3n");
Http.AssertNotSent(r => r.Url.Contains("other.example.com"));
Http.AssertSentCount(1);Http.Response(body, status, headers) serializes non-string bodies as JSON. Each recorded request is a RecordedRequest(Method, Url, Headers, Body). The assertions exist both on the Http facade and on the returned HttpFake (which also has Sent). Http.AssertNothingSent() checks that no request was made.
Storage Fake
Storage.Fake() replaces a disk (the default disk, or the one you name) with a new temporary directory, so tests never touch real files or S3. It needs an active service scope:
var disk = Storage.Fake("public");
var path = await upload.Store("avatars", disk: "public");
disk.AssertExists(path);
disk.AssertMissing("avatars/other.png");The fake is a working local disk, so Storage.Get, Exists, Files, and the rest behave normally on it.
Swapping Any Facade
The fakes above are built on Facade.Swap<T>(instance), which replaces the service a facade resolves for the current async flow. Use it to replace any service facades resolve through Facade.Resolve<T>() with your own test double:
Facade.Swap<IConfiguration>(new ConfigurationBuilder().AddInMemoryCollection().Build());
Config.Set("queue.retry", "5");
Assert.Equal(5, Config.Get("queue.retry", 3));The same async-flow rules apply as for built-in fakes: call it directly in the test method. DotBlaze's TestApp preserves the test execution context for its HTTP requests; a plain WebApplicationFactory does not automatically provide that behavior. Services injected through constructors are not affected by Facade.Swap.
Not Yet Available
There is no fake for Gate (as in Laravel, test authorization with Gate.ForUser(user) and real policies). Mail.Fake(), Notification.Fake(), and Cache.Fake() are described with their features: Mail, Notifications, and Cache.
Complete Example: Failed HTTP Response
Add this complete test to the Blog test project. It makes no network request and needs no database:
// Blog.Tests/HttpFailureTest.cs
using DotBlaze;
using Xunit;
namespace Blog.Tests;
public class HttpFailureTest
{
[Fact]
public async Task A_failed_status_is_explicitly_promoted_to_an_exception()
{
Http.Fake(new()
{
["service.example.test/profile"] = Http.Response(new { message = "Unavailable" }, 503),
});
var response = await Http.Get("https://service.example.test/profile");
Assert.Equal(503, response.Status);
Assert.Throws<HttpRequestException>(() => response.Throw());
Http.AssertSentCount(1);
Http.AssertSent(request => request.Url == "https://service.example.test/profile");
}
}Run dotnet test Blog.Tests --filter FullyQualifiedName~HttpFailureTest. Match the exact expected URL in assertions: an unmatched Http.Fake request returns an empty 200, so a test that checks only “no exception” can hide a typo. A strict AI fake behaves differently and rejects unscripted requests; see AI testing.