Skip to content

[Feature]: Covariant assertions #4830

@ascott18

Description

@ascott18

Problem Statement

It would be nice if source generated assertions (or all assertions?) could be made to be covariant. Right now, an assertion for a base type cannot be used against a derived type because TValue is invariant in IAssertionSource<TValue>.

This somewhat relates to #4825

Proposed Solution

I would like the following assertion to work seamlessly without having to manually cast Impl to IInterface:

public class UnitTest1
{
    [Test]
    public async Task TestWithMemberData()
    {
        Impl item = new Impl { Foo = "bar" };
        await Assert.That(item).HasFoo("bar");
    }
}

public interface IInterface { public string? Foo { get; set; } }

public class Impl : IInterface { public string? Foo { get; set; } }

public static partial class Assertions
{
    [EditorBrowsable(EditorBrowsableState.Never)]
    [GenerateAssertion(ExpectationMessage = "to have foo '{expected}'")]
    public static bool HasFoo(this IInterface target, string expected)
    {
        return target.Foo == expected;
    }
}

Alternatives Considered

No response

Feature Category

Assertions

How important is this feature to you?

Nice to have - would improve my experience

Additional Context

No response

Contribution

  • I'm willing to submit a pull request for this feature

Metadata

Metadata

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions