Skip to content

Instantly share code, notes, and snippets.

@dj-nitehawk
Created March 27, 2025 17:05
Show Gist options
  • Save dj-nitehawk/ae85c63fefb1e8163fdd37ca6dcb7bfd to your computer and use it in GitHub Desktop.
Save dj-nitehawk/ae85c63fefb1e8163fdd37ca6dcb7bfd to your computer and use it in GitHub Desktop.
Integration testing an endpoint that publishes an event
sealed class MyEvent : IEvent
{
public string? Message { get; set; }
}
sealed class MyEventHandler : IEventHandler<MyEvent>
{
public Task HandleAsync(MyEvent e, CancellationToken c)
=> Task.CompletedTask;
}
[HttpGet("publish"), AllowAnonymous]
sealed class MyEndpoint : EndpointWithoutRequest
{
public override async Task HandleAsync(CancellationToken c)
{
var evnt = new MyEvent
{
Message = "hello!"
};
await evnt.PublishAsync(); // "test event receiver" is used to determine if event was published.
await SendAsync("all good!");
}
}
public class Sut : AppFixture<Program>
{
protected override void ConfigureServices(IServiceCollection s)
{
s.RegisterTestEventReceivers(); // register the test event receiver service
}
}
public class MyTests(Sut App) : TestBase<Sut>
{
[Fact]
public async Task Endpoint_Publishes_Correct_Event()
{
//obtain a "test event receiver" for you event type
var receiver = App.Services.GetTestEventReceiver<MyEvent>();
//call the endpoint
var (rsp, _) = await App.Client.GETAsync<MyEndpoint, string>();
rsp.IsSuccessStatusCode.ShouldBeTrue();
//check if "test event receiver" received the event that's supposed to be published by the endpoint.
var received = await receiver.WaitForMatchAsync(e => e.Message == "hello!", timeoutSeconds: 3, ct: Cancellation);
received.Any().ShouldBeTrue();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment