(Deep) comparing an object with a reference in unit tests (C #)

In Unit Test (in Visual Studio 2008), I want to compare the contents of a large object (more precisely, a list of custom types) with a stored link to this object. The goal is to make sure that any subsequent code refactoring creates the same object content.

Discarded idea: The first thought was serialization in XML, and then comparing hard-coded lines or file contents. This will make it easy to find any difference. However, since my types are not XML serializable without hacking, I have to find another solution. I could use binary serialization, but this will no longer read.

Is there a simple and elegant solution?

EDIT: As suggested by Mark Gravell, now I am doing the following:

using (MemoryStream stream = new MemoryStream()) { //create actual graph using only comparable properties List<NavigationResult> comparableActual = (from item in sparsed select new NavigationResult { Direction = item.Direction, /*...*/ VersionIndication = item.VersionIndication }).ToList(); (new BinaryFormatter()).Serialize(stream, comparableActual); string base64encodedActual = System.Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length);//base64 encoded binary representation of this string base64encodedReference = @"AAEAAAD....";//this reference is the expected value Assert.AreEqual(base64encodedReference, base64encodedActual, "The comparable part of the sparsed set is not equal to the reference."); } 

In essence, I first select comparable properties, then encode the graph, and then compare it with a similarly encoded link. Coding provides in-depth comparisons in a simple way. The reason I use base64 encoding is because I can easily save the link in a string variable.

+6
object comparison c # unit-testing visual-studio
source share
3 answers

I would still be inclined to use serialization. But instead of knowing the binary file, just create the expected schedule, serialize it. Now serialize the actual graph and compare the bytes. It is only useful to tell you that there is a difference; you will need an inspection to find what hurts.

+5
source share

I would use hack to compare XML. Or you can use reflection for the automatic properties of the intersection object (but this will intersect ALL of them, as well as some that you might not want).

+1
source share

I would make each inherit type IComparable and provide equality methods that compare each user type and also make the main ICompareble class. Then you can simply compare 2 objects (if you have them in memory when you run the unit tests) If not, then I suggest either serializing or defining the constants that you expect from the reorganized object.

+1
source share

All Articles