Created
August 5, 2024 04:28
-
-
Save dj-nitehawk/8ab7bb4ce5b69152b07b9186d7c40e40 to your computer and use it in GitHub Desktop.
Unit testing an endpoint that publishes an event
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[HttpGet("publish"), AllowAnonymous] | |
sealed class MyEndpoint : EndpointWithoutRequest | |
{ | |
public override async Task HandleAsync(CancellationToken c) | |
{ | |
var evnt = new MyEvent { Message = "hello!" }; | |
await PublishAsync(evnt); | |
await SendAsync("all good!"); | |
} | |
} | |
sealed class MyEvent | |
{ | |
public string? Message { get; set; } | |
} | |
sealed class MyEventHandler : IEventHandler<MyEvent> | |
{ | |
public Task HandleAsync(MyEvent e, CancellationToken c) | |
=> Task.CompletedTask; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class EndpointTests | |
{ | |
[Fact] | |
public async Task Endpoint_Returns_Correct_Response() | |
{ | |
// it's not necessary to register any fake event handlers (subscribers) | |
var ep = Factory.Create<MyEndpoint>(); | |
await ep.HandleAsync(default); | |
ep.Response.Should().Be("all good!"); | |
} | |
[Fact] | |
public async Task Fake_Event_Handler_Executed() | |
{ | |
//a fake event handler can be substituted during testing | |
//in order to assert that an event handler was correctly executed | |
var fakeEventHandler = new FakeEventHandler(); | |
var ep = Factory.Create<MyEndpoint>( | |
ctx => | |
{ | |
ctx.AddTestServices( | |
s => | |
{ | |
s.AddSingleton<IEventHandler<MyEvent>>(fakeEventHandler); | |
}); | |
}); | |
await ep.HandleAsync(default); | |
fakeEventHandler.Message.Should().Be("hello!"); | |
} | |
sealed class FakeEventHandler : IEventHandler<MyEvent> | |
{ | |
public string? Message { get; set; } | |
public Task HandleAsync(MyEvent e, CancellationToken c) | |
{ | |
Message = e.Message; | |
return Task.CompletedTask; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment