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("[email protected]")); | |
var user2 = new User("test", new VerifiedEmail("[email protected]")); | |
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("[email protected]")); | |
var json = JsonSerializer.Serialize(test); | |
Assert.NotNull(json); | |
Assert.Equal("{\"Name\":\"test\",\"Email\":{\"$type\":\"UnverifiedEmail\",\"Value\":\"[email protected]\"}}", json); | |
// Assert.Equal("{\"Name\":\"test\",\"Email\":{\"Value\":\"[email protected]\"}}", json); | |
} | |
[Fact] | |
public void DeserializationNotThrowsTest() | |
{ | |
var test = JsonSerializer.Deserialize<User>("{\"Name\":\"test\",\"Email\":{\"$type\":\"UnverifiedEmail\",\"Value\":\"[email protected]\"}}"); | |
Assert.NotNull(test); | |
Assert.Equal(new User("test", new UnverifiedEmail("[email protected]")), test); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment