Skip to content

Instantly share code, notes, and snippets.

@stormwild
Forked from dj-nitehawk/Program.cs
Created October 1, 2024 09:02
Show Gist options
  • Save stormwild/5d7359b5490aa99a6081459099b9df03 to your computer and use it in GitHub Desktop.
Save stormwild/5d7359b5490aa99a6081459099b9df03 to your computer and use it in GitHub Desktop.
Unit testing an endpoint that executes a command
sealed class MyRequest
{
public int Id { get; set; }
}
public sealed class MyCommand : ICommand<int>
{
public string Identity { get; set; }
}
sealed class MyCommandHandler : ICommandHandler<MyCommand, int>
{
public Task<int> ExecuteAsync(MyCommand command, CancellationToken ct)
=> Task.FromResult(int.Parse(command.Identity));
}
sealed class MyEndpoint : Endpoint<MyRequest, int>
{
public override void Configure()
{
Post("test");
AllowAnonymous();
}
public override async Task HandleAsync(MyRequest r, CancellationToken c)
{
var command = new MyCommand { Identity = r.Id.ToString() };
var result = await command.ExecuteAsync();
await SendAsync(result);
}
}
[Fact]
public async Task Endpoint_With_Command_Inside()
{
//arrange
var ep = Factory.Create<MyEndpoint>();
var req = new MyRequest { Id = 123 };
var fakeHandler = A.Fake<ICommandHandler<MyCommand, int>>();
A.CallTo(() => fakeHandler.ExecuteAsync(A<MyCommand>.Ignored, A<CancellationToken>.Ignored))
.Returns(Task.FromResult(123));
fakeHandler.RegisterForTesting(); // this is the important bit
//act
await ep.HandleAsync(req, default);
//assert
ep.Response.Should().Be(123);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment