<p>Let's say I have a complex .NET class, with lots of arrays and other class object members.  I need to be able to generate a deep clone of this object - so I write a Clone() method, and implement it with a simple BinaryFormatter serialize/deserialize - or perhaps I do the deep clone using some other technique which is more error prone and I'd like to make sure is tested.</p>

<p>OK, so now (ok, I should have done it first) I'd like write tests which cover the cloning.  All the members of the class are private, and my architecture is so good (!) that I haven't needed to write hundreds of public properties or other accessors.  The class isn't IComparable or IEquatable, because that's not needed by the application.  My unit tests are in a separate assembly to the production code.</p>

<p>What approaches do people take to testing that the cloned object is a good copy?   Do you write (or <em>rewrite</em> once you discover the need for the clone) all your unit tests for the class so that they can be invoked with <em>either</em> a 'virgin' object <em>or</em> with a clone of it?   How would you test if part of the cloning wasn't deep enough - as this is just the kind of problem which can give hideous-to-find bugs later?</p>

[{'answer_id': 10956, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>I'd just write a single test to determine if the clone was correct or not.  If the class isn't sealed, you can create a harness for it by extending it, and then exposing all your internals within the child class.  Alternatively, you could use reflection (yech), or use MSTest's Accessor generators.</p>\n\n<p>You need to clone your object and then go through every single property and variable that your object has and determine if it was copied correctly or cloned correctly.  </p>\n"}, {'answer_id': 11069, 'author': 'akmad', 'author_id': 1314, 'author_profile': 'https://Stackoverflow.com/users/1314', 'pm_score': 2, 'selected': False, 'text': "<p>You method of testing will depend on the type of solution you come up with.  If you write some custom cloning code and have to manually implement that in each cloneable type then you should really test the cloning of each one of those types.  Alternatively, if you decide to go a more generic route (where the aforementioned reflection would likely fit in), your tests would only need to test the specific scenarios that you cloning system will have to deal with.</p>\n\n<p>To answer your specific questions:</p>\n\n<blockquote>\n  <p>Do you write (or rewrite once you discover the need for the clone) all your unit tests for the class so that they can be invoked with either a 'virgin' object or with a clone of it?</p>\n</blockquote>\n\n<p>You should have tests for all the methods that can be performed on both the original and cloned objects.  Note that it should be pretty easy to set up a simple test design to support this without manually updating the logic for each test.</p>\n\n<blockquote>\n  <p>How would you test if part of the cloning wasn't deep enough - as this is just the kind of problem which can give hideous-to-find bugs later?</p>\n</blockquote>\n\n<p>It depends on the cloning method you choose.  If you have to manually update the cloneable types then you should test that each type is cloning all (and only) the members you expect.  Whereas, if you are testing a cloning framework I would create some test cloneable types to test each scenario you need to support.</p>\n"}, {'answer_id': 24166, 'author': 'Andrew', 'author_id': 1948, 'author_profile': 'https://Stackoverflow.com/users/1948', 'pm_score': 1, 'selected': False, 'text': '<p>I like to write unit tests that use one of the builtin serializers on the original and the cloned object and then check the serialized representations for equality (for a binary formatter, I can just compare the byte arrays).  This works great in cases where the object is still serializable, and I\'m only changing to a custom deep clone for perf reasons.</p>\n\n<p>Furthermore, I like to add a debug mode check to all of my Clone implementations using something like this</p>\n\n<pre><code>[Conditional("DEBUG")]\npublic static void DebugAssertValueEquality&lt;T&gt;(T current, T other, bool expected, \n                                               params string[] ignoredFields) {\n    if (null == current) \n    { throw new ArgumentNullException("current"); }\n    if (null == ignoredFields)\n    { ignoredFields = new string[] { }; }\n\n    FieldInfo lastField = null;\n    bool test;\n    if (object.ReferenceEquals(other, null))\n    { Debug.Assert(false == expected, "The other object was null"); return; }\n    test = true;\n    foreach (FieldInfo fi in current.GetType().GetFields(BindingFlags.Instance)) {\n        if (test = false) { break; }\n        if (0 &lt;= Array.IndexOf&lt;string&gt;(ignoredFields, fi.Name))\n        { continue; }\n        lastField = fi;\n        object leftValue = fi.GetValue(current);\n        object rightValue = fi.GetValue(other);\n        if (object.ReferenceEquals(null, leftValue)) {\n            if (!object.ReferenceEquals(null, rightValue))\n            { test = false; }\n        }\n        else if (object.ReferenceEquals(null, rightValue))\n        { test = false; }\n        else {\n            if (!leftValue.Equals(rightValue))\n            { test = false; }\n        }\n    }\n    Debug.Assert(test == expected, string.Format("field: {0}", lastField));\n}\n</code></pre>\n\n<p>This method relies on an accurate implementation of Equals on any nested members, but in my case anything that is cloneable is also equatable</p>\n'}, {'answer_id': 2497556, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>There's a really obvious solution that doesn't take nearly as much work:</p>\n\n<ol>\n<li>Serialize the object into a binary format.</li>\n<li>Clone the object.</li>\n<li>Serialize the clone into a binary format.</li>\n<li>Compare the bytes.</li>\n</ol>\n\n<p>Assuming that serialization works - and it better because you are using it to clone - this should be easy to maintain.  In fact, it will be encapsulated from changes to the structure of your class completely.</p>\n"}, {'answer_id': 12477641, 'author': 'EricSchaefer', 'author_id': 8976, 'author_profile': 'https://Stackoverflow.com/users/8976', 'pm_score': 1, 'selected': False, 'text': '<p>I would usually implement <code>Equals()</code> for comparing the two objects in depth. You might not need it in your production code but it might still come in handy later and the test code is much cleaner.</p>\n'}, {'answer_id': 31139080, 'author': 'Thulani Chivandikwa', 'author_id': 611628, 'author_profile': 'https://Stackoverflow.com/users/611628', 'pm_score': 0, 'selected': False, 'text': '<p>Here is a sample of how I implemented this a while back, although this will need to be tailored to the scenario. In this case we had a nasty object chain that could easily change and the clone was used as a very critical prototype implementation and so I had to patch (hack) this test together.</p>\n\n<pre><code>public static class TestDeepClone\n    {\n        private static readonly List&lt;long&gt; objectIDs = new List&lt;long&gt;();\n        private static readonly ObjectIDGenerator objectIdGenerator = new ObjectIDGenerator();\n\n        public static bool DefaultCloneExclusionsCheck(Object obj)\n        {\n            return\n                obj is ValueType ||\n                obj is string ||\n                obj is Delegate ||\n                obj is IEnumerable;\n        }\n\n        /// &lt;summary&gt;\n        /// Executes various assertions to ensure the validity of a deep copy for any object including its compositions\n        /// &lt;/summary&gt;\n        /// &lt;param name="original"&gt;The original object&lt;/param&gt;\n        /// &lt;param name="copy"&gt;The cloned object&lt;/param&gt;\n        /// &lt;param name="checkExclude"&gt;A predicate for any exclusions to be done, i.e not to expect IPolicy items to be cloned&lt;/param&gt;\n        public static void AssertDeepClone(this Object original, Object copy, Predicate&lt;object&gt; checkExclude)\n        {\n            bool isKnown;\n            if (original == null) return;\n            if (copy == null) Assert.Fail("Copy is null while original is not", original, copy);\n\n            var id = objectIdGenerator.GetId(original, out isKnown); //Avoid checking the same object more than once\n            if (!objectIDs.Contains(id))\n            {\n                objectIDs.Add(id);\n            }\n            else\n            {\n                return;\n            }\n\n            if (!checkExclude(original))\n            {\n                Assert.That(ReferenceEquals(original, copy) == false);\n            }\n\n            Type type = original.GetType();\n            PropertyInfo[] propertyInfos = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);\n            FieldInfo[] fieldInfos = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);\n\n            foreach (PropertyInfo memberInfo in propertyInfos)\n            {\n                var getmethod = memberInfo.GetGetMethod();\n                if (getmethod == null) continue;\n                var originalValue = getmethod.Invoke(original, new object[] { });\n                var copyValue = getmethod.Invoke(copy, new object[] { });\n                if (originalValue == null) continue;\n                if (!checkExclude(originalValue))\n                {\n                    Assert.That(ReferenceEquals(originalValue, copyValue) == false);\n                }\n\n                if (originalValue is IEnumerable &amp;&amp; !(originalValue is string))\n                {\n                    var originalValueEnumerable = originalValue as IEnumerable;\n                    var copyValueEnumerable = copyValue as IEnumerable;\n                    if (copyValueEnumerable == null) Assert.Fail("Copy is null while original is not", new[] { original, copy });\n                    int count = 0;\n                    List&lt;object&gt; items = copyValueEnumerable.Cast&lt;object&gt;().ToList();\n                    foreach (object o in originalValueEnumerable)\n                    {\n                        AssertDeepClone(o, items[count], checkExclude);\n                        count++;\n                    }\n                }\n                else\n                {\n                    //Recurse over reference types to check deep clone success\n                    if (!checkExclude(originalValue))\n                    {\n                        AssertDeepClone(originalValue, copyValue, checkExclude);\n                    }\n\n                    if (originalValue is ValueType &amp;&amp; !(originalValue is Guid))\n                    {\n                        //check value of non reference type\n                        Assert.That(originalValue.Equals(copyValue));\n                    }\n                }\n\n            }\n\n            foreach (FieldInfo fieldInfo in fieldInfos)\n            {\n                var originalValue = fieldInfo.GetValue(original);\n                var copyValue = fieldInfo.GetValue(copy);\n                if (originalValue == null) continue;\n                if (!checkExclude(originalValue))\n                {\n                    Assert.That(ReferenceEquals(originalValue, copyValue) == false);\n                }\n\n                if (originalValue is IEnumerable &amp;&amp; !(originalValue is string))\n                {\n                    var originalValueEnumerable = originalValue as IEnumerable;\n                    var copyValueEnumerable = copyValue as IEnumerable;\n                    if (copyValueEnumerable == null) Assert.Fail("Copy is null while original is not", new[] { original, copy });\n                    int count = 0;\n                    List&lt;object&gt; items = copyValueEnumerable.Cast&lt;object&gt;().ToList();\n                    foreach (object o in originalValueEnumerable)\n                    {\n                        AssertDeepClone(o, items[count], checkExclude);\n                        count++;\n                    }\n                }\n                else\n                {\n                    //Recurse over reference types to check deep clone success\n                    if (!checkExclude(originalValue))\n                    {\n                        AssertDeepClone(originalValue, copyValue, checkExclude);\n                    }\n                    if (originalValue is ValueType &amp;&amp; !(originalValue is Guid))\n                    {\n                        //check value of non reference type\n                        Assert.That(originalValue.Equals(copyValue));\n                    }\n                }\n            }\n        }\n    }\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/10949', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/987/']