You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Value equality on subset of object properties #4687
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:
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:
Do individual equality assertions on those properties, which doesn't scale very cleanly for real-world objects with many properties.
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(newThing{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 😅).
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());
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.
@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
I added a PR that adds 2 new UsingPropertiesComparer methods:
Only compare the properties specified: UsingPropertiesComparerOnlyProperties(params string[] propertiesToCompare)
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.
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(newThing{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.
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.
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.
@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 🤷♂️
@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.
Activity
stevenaw commentedon Apr 14, 2024
This is a neat idea, so I'm going to label it
ideafor the team to consider.One thought about option 2 here is that if the
expectedis 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:
Rabadash8820 commentedon Apr 14, 2024
Ooh that's a cool idea. I assumed some
Expressionmagic would be necessary for NUnit to distinguish whether a property was provided or not, but simply iterating the provided properties on an anonymous (ordynamic) object could be simpler. FWIW, I got this idea fromts-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.mikkelbu commentedon Apr 14, 2024
@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
Or perhaps using
ExcludingMissingMembersto only compare the properties that exists in both objects that are being comparedanders9ustafsson commentedon Jan 17, 2025
Could it be an alternative to add an overload of
UsingPropertiesComparer, e.g. like this:UsingPropertiesComparer(params string[] propertiesToIgnore)?manfred-brands commentedon Jan 17, 2025
I added a PR that adds 2 new
UsingPropertiesComparermethods:UsingPropertiesComparerOnlyProperties(params string[] propertiesToCompare)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.
Rabadash8820 commentedon Jan 17, 2025
@manfred-brands Thanks for opening that PR!
I think repeating "Properties" in the names should be avoided. Maybe
UsingIncludedPropertiesComparerandUsingExcludedPropertiesComparer? The params would then be similarly namedincludedPropertyNamesandexcludedPropertyNames(I prefer havingNamesin the name to self-document why they are strings).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: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 likeAmbiguousMatchExceptioncould 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.manfred-brands commentedon Jan 18, 2025
I prefer to have all method starting with
UsingPropertiesComparerso they are easier to find.I came up with:
UsingPropertiesComparerUsingOnly(params string[] propertyNamesToUse)andUsingPropertiesComparerExcluding(params string[] propertyNamesToExclude)I added support for Expressions, but at the moment you have to manually specify the type again:
We know the type of instance at compile time, but it is lost as the
EqualConstraintitself is not generic.I'll see if I can fix that at least for this use case later this weekend.
manfred-brands commentedon Jan 18, 2025
Ok, you no longer have to specify the type for the expression explicitly:
Rabadash8820 commentedon Jan 21, 2025
@manfred-brands That looks awesome, nice work adding that generic support!
One final naming thought: changing
*UsingOnlyto*Includingwould look more consistent with*Excluding, IMO.manfred-brands commentedon Jan 21, 2025
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.
Rabadash8820 commentedon Jan 21, 2025
@manfred-brands Fair point. Maybe just
*Onlyinstead of*UsingOnlyso that each method name has the same number of words? I'm just nitpicking now though; the current names are probably fine 🤷♂️manfred-brands commentedon Feb 22, 2025
@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:
Rabadash8820 commentedon Feb 22, 2025
@manfred-brands Looks awesome! Tysm for your effort on this!