Created
September 20, 2023 07:22
-
-
Save tomohisa/71f28c77061a3cff9ee5e587f73a3578 to your computer and use it in GitHub Desktop.
Interface property serialization / deserialization using JsonDerivedType
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
[JsonDerivedType(typeof(UnverifiedEmail), nameof(UnverifiedEmail))] | |
[JsonDerivedType(typeof(VerifiedEmail), nameof(VerifiedEmail))] | |
public interface IUserEmail; | |
public record UnverifiedEmail(string Value) : IUserEmail; | |
public record VerifiedEmail(string Value) : IUserEmail; | |
public record User(string Name, IUserEmail Email); | |
public class UserEmailTest | |
{ | |
private readonly ITestOutputHelper _testOutputHelper; | |
public UserEmailTest(ITestOutputHelper testOutputHelper) => _testOutputHelper = testOutputHelper; | |
[Fact] | |
public void TestingEmail() | |
{ | |
var user = new User("test", new UnverifiedEmail("test@example.com")); | |
var user2 = new User("test", new VerifiedEmail("test@example.com")); | |
if (user.Email is VerifiedEmail email) | |
{ | |
SendEmail(email); | |
} | |
if (user2.Email is VerifiedEmail email2) | |
{ | |
SendEmail(email2); | |
} | |
} | |
private void SendEmail(VerifiedEmail email) | |
{ | |
_testOutputHelper.WriteLine("sending email to " + email.Value + "..."); | |
} | |
[Fact] | |
public void SerializationSucceedsTest() | |
{ | |
var test = new User("test", new UnverifiedEmail("test@example.com")); | |
var json = JsonSerializer.Serialize(test); | |
Assert.NotNull(json); | |
Assert.Equal("{\"Name\":\"test\",\"Email\":{\"$type\":\"UnverifiedEmail\",\"Value\":\"test@example.com\"}}", json); | |
// Assert.Equal("{\"Name\":\"test\",\"Email\":{\"Value\":\"test@example.com\"}}", json); | |
} | |
[Fact] | |
public void DeserializationNotThrowsTest() | |
{ | |
var test = JsonSerializer.Deserialize<User>("{\"Name\":\"test\",\"Email\":{\"$type\":\"UnverifiedEmail\",\"Value\":\"test@example.com\"}}"); | |
Assert.NotNull(test); | |
Assert.Equal(new User("test", new UnverifiedEmail("test@example.com")), test); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment