Skip to content

Instantly share code, notes, and snippets.

@dj-nitehawk
Created October 6, 2023 10:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dj-nitehawk/f0c5c95c57ac1f1d15c936e9d87734b0 to your computer and use it in GitHub Desktop.
Save dj-nitehawk/f0c5c95c57ac1f1d15c936e9d87734b0 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