JasperFx/alba

Some issues with minimal api

hartmark opened this issue · 3 comments

I have this small Program.cs:

using Microsoft.AspNetCore.Mvc;

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.MapGet("/", () => Results.Ok(new Response { Foo= "Hello World!" }));
app.MapPost("/", ([FromBody] Request request) => Results.Ok(new Response { Foo = request.Foo}));
app.Run();

public class Request
{
    public string Foo { get; set; }
}

public class Response
{
    public string Foo { get; set; }
}

And this TestClass:

using System.Net;
using Alba;
using Xunit;

namespace Test;

public class UnitTest1
{
    [Fact]
    public async void Test_Get()
    {
        await using var host = await AlbaHost.For<Program>(x =>
        {
            x.ConfigureServices((context, services) =>
            {
            });
        });
        
        var result = await host.Scenario(_ =>
        {
            _.Get.Url("/");
            _.ContentTypeShouldBe($"{MimeType.Json}; charset=utf-8");
            _.StatusCodeShouldBe(HttpStatusCode.OK);
        });

        var response = result.ReadAsJson<Response>();
        Assert.NotNull(response);
        Assert.Equal("Hello World!", response!.Foo);
    }
    
    [Fact]
    public async void Test_Post()
    {
        await using var host = await AlbaHost.For<Program>(x =>
        {
            x.ConfigureServices((context, services) =>
            {
            });
        });
        
        Request request = new Request
        {
            Foo = "Post!!"
        };

        var result = await host.Scenario(_ =>
        {
            _.Post.Json(request).ToUrl("/");
            _.ContentTypeShouldBe($"{MimeType.Json}; charset=utf-8");
            _.StatusCodeShouldBe(HttpStatusCode.OK);

        });
        
        var response = result.ReadAsJson<Response>();
        Assert.NotNull(response);
        Assert.Equal(request.Foo, response!.Foo);
    }
}

When running it complains about:
Alba was not able to find a registered formatter for content type 'application/json'. Either specify the body contents explicitly, or try registering 'services.AddMvcCore()'

Is there a better way to add the serializer settings than adding this line to Program.cs?
builder.Services.AddMvcCore();

However, the Test_Get passes but the Test_Post fails with this error now:

Alba.ScenarioAssertionException: Expected status code 200, but was 400

Alba.ScenarioAssertionException
Expected status code 200, but was 400
Expected a single header value of 'content-type'='application/json; charset=utf-8', but the actual value was 'text/plain; charset=utf-8'


Actual body text was:

Microsoft.AspNetCore.Http.BadHttpRequestException: Required parameter "Request request" was not provided from body.
   at Microsoft.AspNetCore.Http.RequestDelegateFactory.Log.RequiredParameterNotProvided(HttpContext httpContext, String parameterTypeName, String parameterName, String source, Boolean shouldThrow)
   at lambda_method26(Closure , Object , HttpContext , Object )
   at Microsoft.AspNetCore.Http.RequestDelegateFactory.<>c__DisplayClass46_3.<<HandleRequestBodyAndCompileRequestDelegate>b__2>d.MoveNext()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

HEADERS
=======
Host: localhost
Content-Type: application/json
Content-Length: 16
accept: application/json


   at Alba.Scenario.RunAssertions(HttpContext context) in /_/src/Alba/Scenario.cs:line 256
   at Alba.AlbaHost.Scenario(Action`1 configure) in /_/src/Alba/AlbaHost.cs:line 231
   at Alba.AlbaHost.Scenario(Action`1 configure) in /_/src/Alba/AlbaHost.cs:line 235
   at Test.UnitTest1.Test_Post() in /home/markus/code/minimal-api/Test/UnitTest1.cs:line 47
   at Test.UnitTest1.Test_Post() in /home/markus/code/minimal-api/Test/UnitTest1.cs:line 57
   at System.Threading.Tasks.Task.<>c.<ThrowAsync>b__128_0(Object state)
   at Xunit.Sdk.AsyncTestSyncContext.<>c__DisplayClass7_0.<Post>b__1(Object _) in C:\Dev\xunit\xunit\src\xunit.execution\Sdk\AsyncTestSyncContext.cs:line 75

minimal-api.tar.gz
Attached example project

Blech folks, I've hit the same thing. I'll try to address it soon, or at least document a workaround

I'm about to push a fix, with a big assist from @Hawxy who did the research