Created
October 6, 2023 10:43
-
-
Save dj-nitehawk/f0c5c95c57ac1f1d15c936e9d87734b0 to your computer and use it in GitHub Desktop.
Unit testing an endpoint that executes a command
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
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); | |
} | |
} |
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
[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