I have a problem with integration test (made with WebApplicationFactory) that cannot parse back to JSON obtained response. I have seen some similar issues reported here but nothing found so far was helpful.
Generally, for the test purpose there is this very simple Program.cs:
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Http.Json;
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddControllers();
builder.Services.Configure<JsonOptions>(options =>
{
options.SerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
var app = builder.Build();
app.MapControllers();
app.MapGet("/test", () => new SomeView { Name = "SomeName", SomeEnum = SomeEnum.No });
app.Run();
public class SomeView
{
public string Name { get; set; }
public SomeEnum SomeEnum { get; set; }
}
public enum SomeEnum
{
Yes = 1,
No
}
And the following very simple test:
public class UnitTest
{
[Fact]
public async Task Test1()
{
var factory = new WebApplicationFactory<Program>();
var client = factory.CreateClient();
var response = await client.GetAsync("/test");
var result = await response.Content.ReadFromJsonAsync<SomeView>(new JsonSerializerOptions()
{
Converters = { new JsonStringEnumConverter() }
});
Assert.Equal(SomeEnum.No, result.SomeEnum);
}
}
The issue is - running that test is failed since:
Xunit.Sdk.EqualException
Assert.Equal() Failure
Expected: No
Actual: 0
The whole object have nulled properties. Without providing JsonSerializerOptions the application throws another exception that it is not possible to parse that SomeEnum. However, if I will try to get the response by:
var result = await response.Content.ReadAsStringAsync()
The result is correctly set to the:
{"name":"SomeName","someEnum":"No"}
Any suggestion what is done incorrectly here would be appreciated.
Names of properties in json are in different case compared to the properties of
SomeView. Either fix it withJsonPropertyNameAttributeor provide naming policy:Another option is to reuse the web defaults for serializer settings: