I am writing an integration test for an Api Controller in ASP.NET Core 3.0. The test is for a route that responds with a list of entities. When I try to make the assertions on the response content, there is a divergence in the way the DateTime properties are being serialized.
I have tried using a custom JsonConverter in the test:
public class DateTimeConverter : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return DateTime.Parse(reader.GetString());
}
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString("yyyy-MM-ddThh:mm:ss.ffffff"));
}
}
The problem is that this converter does not truncate trailing zeroes, while the actual response does. So, the test has a 1 in 10 chance of failing.
This is the failing test:
[Fact]
public async Task GetUsers()
{
using var clientFactory = new ApplicationFactory<Startup>();
using var client = clientFactory.CreateClient();
using var context = clientFactory.CreateContext();
var user1 = context.Users.Add(new User()).Entity;
var user2 = context.Users.Add(new User()).Entity;
context.SaveChanges();
var users = new List<User> { user1, user2 };
var jsonSerializerOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
var serializedUsers = JsonSerializer.Serialize(users, jsonSerializerOptions);
var response = await client.GetAsync("/users");
var responseBody = await response.Content.ReadAsStringAsync();
Assert.Equal(serializedUsers, responseBody);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
I expected the test to pass, but I get this error instead:
Error Message:
Assert.Equal() Failure
↓ (pos 85)
Expected: ···1-05T22:14:13.242771-03:00","updatedAt"···
Actual: ···1-05T22:14:13.242771","updatedAt"···
I didn't configure any serialization options in the controller's real implementation.
How can I correctly implement this integration test? Is there a straightforward way to serialize the list in the test using the same options of the real controller?