Skip to content

Instantly share code, notes, and snippets.

  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ByteDev/279e71a8263b143c95c8fea7a24c5a19 to your computer and use it in GitHub Desktop.
using System;
using System.Text.Json;
using NUnit.Framework;

// ...

public class TestEntity
{
    [JsonPropertyName("datetime")]
    public DateTime MyDateTime { get; set; }
}

// ...

[TestFixture]
public class UnixEpochTimeToDateTimeJsonConverterTests
{
    private const string Json = "{\"datetime\":1641974376}";

    private JsonSerializerOptions _options;

    [SetUp]
    public void SetUp()
    {
        var sut = new UnixEpochTimeToDateTimeJsonConverter();
    
        _options = new JsonSerializerOptions();
        _options.Converters.Add(sut);
    }

    [Test]
    public void WhenRead_ThenSetDateTime()
    {
        var result = JsonSerializer.Deserialize<TestEntity>(Json, _options);

        Assert.That(result.MyDateTime, Is.EqualTo(new DateTime(2022, 1, 12, 7, 59, 36)));
        Assert.That(result.MyDateTime.Kind, Is.EqualTo(DateTimeKind.Utc));
    }

    [Test]
    public void WhenWrite_ThenWriteJsonUnixEpoch()
    {
        var entity = new TestEntity
        {
            MyDateTime = new DateTime(2022, 1, 12, 7, 59, 36, DateTimeKind.Utc)
        };

        var result = JsonSerializer.Serialize(entity, _options);

        Assert.That(result, Is.EqualTo(Json));
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment