samedi 26 décembre 2020

MemberData throws exception when property throws exception

There is the following code:

public class User
{
    private Address _address;

    public string Name { get; set; }
    public int Age { get; set; }
    public int Score { get; set; }
    public bool HasAddress => _address != null;
    public Address Address => _address ?? throw new Exception();
}

public class Address
{
    // ...
}

And Score_ReturnsCorrectValue unit-test to test User:

public class UserTests
{
    [Theory]
    [MemberData(nameof(ReturnsCorrectValueTestCases))]
    public void Score_ReturnsCorrectValue(User user, int expectedScore)
    {
        // Act
        // ...

        // Assert
        user.Score.Should().Be(expectedScore);
    }

    public static IEnumerable<object[]> ReturnsCorrectValueTestCases()
    {
        var user1 = new User { Age = 65 };
        var user2 = new User { Age = 21 };

        yield return new object[]
        {
            new object[] {user1, 100},
            new object[] {user2, 50}
        };
    }
}

xUnit runner failed on User.Address property:

enter image description here

So, look like, MemberData works via reflection and it doesn't like such property which can throw an exception.


I'm new to MemberData attribute. Is it possible to change the unit-test in some way without changing User.Address logic?

Aucun commentaire:

Enregistrer un commentaire