My Assert.Equal() for an anonymous object is returning false, however very carefully inspecting the properties by hand in the debugger everything seems fine.

It doesn't complain about the properties per say, only the following (which if you compare in a diffing tool is exactly the same).

Expected: { id = 1, name = , children = System.Collections.Generic.List1[System.Collections.Generic.Dictionary2[System.String,System.String]] } (<>f__AnonymousType13[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Collections.Generic.List1[[System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]])


Actual: { id = 1, name = , children = System.Collections.Generic.List1[System.Collections.Generic.Dictionary2[System.String,System.String]] } (<>f__AnonymousType13[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Collections.Generic.List1[[System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]])

有帮助吗?

解决方案

After reading:

Anonymous types unify within an assembly, Part One

Anonymous Types Unify Within An Assembly, Part Two

From what I can tell; within an assembly if an anonymous object has the same properties in the same order, then they can be compared as the same type. But in separate assemblies they cannot be compared as the same type.

After lots of trial and error, I've instead used the CompareObjects open source project to have more control of the equality check. It's not ideal, as I'd prefer to stick to Assert... but I need to work with objects in my context, so this is pretty elegant solution for my problem.

 CompareObjects compareObjects = new CompareObjects();
 compareObjects.MaxDifferences = 1000;
 compareObjects.IgnoreObjectTypes = true; //handles anonymous types
 bool isSame = compareObjects.Compare(exepected, actual);
 Assert.True(isSame, compareObjects.DifferencesString);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top