Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Assert.Equivalent fails with ArgumentException ("An item with the same key has already been added.") when baseclass uses "new" on property #3193

Open
Joost-Jens-Luminis opened this issue Feb 28, 2025 · 1 comment · May be fixed by xunit/assert.xunit#69

Comments

@Joost-Jens-Luminis
Copy link

When a subclass overwrites a parent's class property with a more specific type, Assert.Equivalent fails with the following exception:
System.ArgumentException : An item with the same key has already been added. Key: ID

This appears to go wrong in AssertHelper.cs here:

Image

The following example shows the issue:

[Fact]
public void TestMyClass()
{
    MyClass c1 = new MyClass("123");
    MyClass c2 = new MyClass("123");

    Assert.Equivalent(c1, c2);
}

public abstract class MyDomainBase<T>
    where T : MyDomainBase<T>
{
    protected MyDomainBase(object id)
    {
        ID = id;
    }

    public object ID { get; }
}

public abstract class MyDomainBase<T, TIdentifier> : MyDomainBase<T>
    where T : MyDomainBase<T, TIdentifier>
{
    protected MyDomainBase(TIdentifier id) : base(id)
    {
        ID = id;
    }

    public new TIdentifier ID { get; }
}

public class MyClass : MyDomainBase<MyClass, string>
{
    public MyClass(string id) : base(id)
    {
    }
}

Edit; styling and formatting.

@Joost-Jens-Luminis
Copy link
Author

Replacing the code part I meantioned above in AssertHelper with the following changes seem to fix the issue:

  return
      fieldGetters
          .Concat(propertyGetters)
          .GroupBy(g=> g.name)
          .ToDictionary(g => g.Key, g => g.First().getter);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
1 participant