Skip to content

Value equality on subset of object properties #4687

Closed

Description

@Rabadash8820

It would be pretty handy if there was a way to do value equality on a subset of an object's properties. For example, suppose I have the following class definition:

class Thing {
    public int SomeInt { get; set; }
    public double SomeDouble { get; set; }
    public string SomeString { get; set; }
}

and a method that returns a Thing. Let's say that the method sets non-default values for all the object's properties, but I only care about the values of the return object's numeric properties (SomeInt and SomeDouble). My options are to:

  1. Do individual equality assertions on those properties, which doesn't scale very cleanly for real-world objects with many properties.

    Assert.That(thing.SomeInt, Is.EqualTo(expectedInt));
    Assert.That(thing.SomeDouble, Is.EqualTo(expectedDouble));
  2. Define an "expected" object and use equality assertion with UsingPropertiesComparer, which requires me to include those other non-default values in my expected object, even though my test really only cares about the two numeric properties (also doesn't scale well for objects with many properties).

    Assert.That(thing, Is.EqualTo(new Thing {
        SomeInt = 5,
        SomeDouble = 5d,
        SomeString = "bla bla don't care",
    }).UsingPropertiesComparer());

It would be great if NUnit had a version of UsingPropertiesComparer that only compared a subset of Thing's properties. Perhaps using an Expression or collection of Expressions for consumers to specify the properties that they care about. Something like the following would be awesome, as the test code would not have to change as more properties are added to Thing (obviously with better naming 😅).

Assert.That(thing, Is.EqualTo(new Thing {
    SomeInt = 5,
    SomeDouble = 5d,
}).UsingPropertiesComparerButOnlyOnThePropertiesSpecifiedAbove());

Activity

  1. stevenaw commented on Apr 14, 2024

    @stevenaw
    Member

    This is a neat idea, so I'm going to label it idea for the team to consider.
    One thought about option 2 here is that if the expected is the same POCO type and not all properties are specified then it may be tough for the framework to understand if a prop not listed, and thus with a default value, should be considered or not. One alternative option which could be considered is passing an anonymous object instead.

    Perhaps some variation involving:

    Assert.That(thing, Is.EqualTo(new {
        SomeInt = 5,
        SomeDouble = 5d,
        SomeString = "bla bla don't care",
    }).UsingPropertiesComparer());
  2. Rabadash8820 commented on Apr 14, 2024

    @Rabadash8820
    Author

    Ooh that's a cool idea. I assumed some Expression magic would be necessary for NUnit to distinguish whether a property was provided or not, but simply iterating the provided properties on an anonymous (or dynamic) object could be simpler. FWIW, I got this idea from ts-mockito (a TypeScript mocking library inspired by Java's Mockito library), where such "sub-equality" comparisons are possible. This may be due to the "duck typing" that TS uses under the hood, so I wasn't sure if this would be possible in .NET, but hopefully it will be with one of the above approaches.

  3. mikkelbu commented on Apr 14, 2024

    @mikkelbu
    Member

    @Rabadash8820 Usually, when I have to do assertions like this, then I use an assertion framework - e.g. FluentAssertions. Using FluentAssertions can specify it like this

    orderDto.Should().BeEquivalentTo(order, options => options
        .Including(o => o.OrderNumber)
        .Including(pi => pi.Name == "Date"));

    Or perhaps using ExcludingMissingMembers to only compare the properties that exists in both objects that are being compared

  4. anders9ustafsson commented on Jan 17, 2025

    @anders9ustafsson

    Could it be an alternative to add an overload of UsingPropertiesComparer, e.g. like this: UsingPropertiesComparer(params string[] propertiesToIgnore)?

  5. manfred-brands commented on Jan 17, 2025

    @manfred-brands
    Member

    I added a PR that adds 2 new UsingPropertiesComparer methods:

    1. Only compare the properties specified:
      UsingPropertiesComparerOnlyProperties(params string[] propertiesToCompare)
    2. Compare all except the properties specified:
      UsingPropertiesComparerExcludingProperties(params string[] propertiesToIgnore)
      Note that excluding all properties result in an error as there is no comparer.

    I marked the PR as WIP as I'm open to different names.

    I'm not in favour to use reflection at runtime to find property names.

    There is one question, should the comparer throw an exception if the user specifies properties that not actually exist.

    One note, the property names work recursively on aggregated classes.

  6. Rabadash8820 commented on Jan 17, 2025

    @Rabadash8820
    Author

    @manfred-brands Thanks for opening that PR!

    I'm open to different names.

    I think repeating "Properties" in the names should be avoided. Maybe UsingIncludedPropertiesComparer and UsingExcludedPropertiesComparer? The params would then be similarly named includedPropertyNames and excludedPropertyNames (I prefer having Names in the name to self-document why they are strings).

    I'm not in favour to use reflection at runtime to find property names.

    To avoid reflection (or at least make things less "stringly typed" for callers), could you maybe take an array of LINQ Expressions instead? Then calls would look like this:

    Assert.That(thing, Is.EqualTo(new Thing {
        SomeInt = 5,
        SomeDouble = 5d,
    }).UsingPropertiesComparer([
        x => x.SomeInt,
        x => x.SomeDouble,
        x => x.SomeObject.NestedProperty
    ]));

    should the comparer throw an exception if the user specifies properties that not actually exist

    The Expression-based signature described above would make this moot (users would just get a compiler error if they use a missing property name). However, if you stick with string names then, personally, yes I think it should throw for missing properties. Presumably, InvalidOperationException, AssertionException, or some other more appropriate exception. Other reflection exceptions like AmbiguousMatchException could just be re-thrown. By comparison, the .NET Type.GetProperty() method just returns null if the property is not found. In this case, however, a missing property would clearly mean that somebody either wrote their test wrong or removed/updated a type property without updating the test. In either case, I think the test should fail noisily.

  7. manfred-brands commented on Jan 18, 2025

    @manfred-brands
    Member

    I think repeating "Properties" in the names should be avoided. Maybe UsingIncludedPropertiesComparer and UsingExcludedPropertiesComparer? The params would then be similarly named includedPropertyNames and excludedPropertyNames (I prefer having Names in the name to self-document why they are strings).

    I prefer to have all method starting with UsingPropertiesComparer so they are easier to find.
    I came up with: UsingPropertiesComparerUsingOnly(params string[] propertyNamesToUse) and UsingPropertiesComparerExcluding(params string[] propertyNamesToExclude)

    I added support for Expressions, but at the moment you have to manually specify the type again:

    Assert.That(new ClassWithSomeToleranceAwareMembers(2, 1.1, "1.1", zero),
                Is.EqualTo(instance).UsingPropertiesComparerExcluding<ClassWithSomeToleranceAwareMembers>(
                    x => x.ValueA,
                    x => x.ValueB,
                    x => x.ValueC));
    

    We know the type of instance at compile time, but it is lost as the EqualConstraint itself is not generic.
    I'll see if I can fix that at least for this use case later this weekend.

  8. manfred-brands commented on Jan 18, 2025

    @manfred-brands
    Member

    Ok, you no longer have to specify the type for the expression explicitly:

    Assert.That(new ClassWithSomeToleranceAwareMembers(2, 1.1, "1.1", zero),
                Is.EqualTo(instance).UsingPropertiesComparerUsingOnly(
                    x => x.Chained));
    
    Assert.That(persons, Does.Contain(new Person { Name = florence })
                             .UsingPropertiesComparerUsingOnly(x => x.Name));
    Assert.That(persons, Does.Contain(new Person { Name = florence })
                             .UsingPropertiesComparerExcluding(x => x.Age));
    
  9. Rabadash8820 commented on Jan 21, 2025

    @Rabadash8820
    Author

    @manfred-brands That looks awesome, nice work adding that generic support!

    One final naming thought: changing *UsingOnly to *Including would look more consistent with *Excluding, IMO.

  10. manfred-brands commented on Jan 21, 2025

    @manfred-brands
    Member

    One final naming thought: changing *UsingOnly to *Including would look more consistent with *Excluding, IMO.

    I disagree.

    Although including complements excluding, include to me means "in addition of".
    Excluding means: The standard properties minus the ones listed.
    Including would mean: The standard properties plus the ones listed.
    Only means only the ones listed.

  11. Rabadash8820 commented on Jan 21, 2025

    @Rabadash8820
    Author

    @manfred-brands Fair point. Maybe just *Only instead of *UsingOnly so that each method name has the same number of words? I'm just nitpicking now though; the current names are probably fine 🤷‍♂️

  12. manfred-brands commented on Feb 22, 2025

    @manfred-brands
    Member

    @Rabadash8820 I added more configuration options which made me change the syntax from separate methods to a configuration callback which allows more flexibility when more options are added.

    The syntax is now:

    Assert.That(new ClassWithSomeToleranceAwareMembers(2, 1.1, "1.1", zero),
                Is.EqualTo(instance)
                  .UsingPropertiesComparer(c => c.Using(x => x.Chained)));
    
    Assert.That(persons, Does.Contain(new Person { Name = florence })
                             .UsingPropertiesComparer(c => c.Using(x => x.Name)));
    Assert.That(persons, Does.Contain(new Person { Name = florence })
                             .UsingPropertiesComparer(c => c.Excluding(x => x.Age)));
  13. Rabadash8820 commented on Feb 22, 2025

    @Rabadash8820
    Author

    @manfred-brands Looks awesome! Tysm for your effort on this!

  14. added this to the 4.4 milestone on Mar 2, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions