深度克隆的单元测试

时间:2008-08-14 12:49:03

标签: c# .net unit-testing

假设我有一个复杂的.NET类,包含许多数组和其他类对象成员。我需要能够生成这个对象的深层克隆 - 所以我编写了一个Clone()方法,并使用一个简单的BinaryFormatter序列化/反序列化来实现它 - 或者我可能使用其他一些更容易出错的技术来进行深度克隆我想确保经过测试。

好的,现在(好吧,我应该先做)我想写一些涵盖克隆的测试。该类的所有成员都是私有的,我的架构非常好(!),我不需要编写数百个公共属性或其他访问器。该类不是IComparable或IEquatable,因为应用程序不需要它。我的单元测试与生产代码分开组装。

人们采用什么方法来测试克隆对象是一个好的副本?你是否发现了(或者重写,一旦你发现需要克隆)所有的单元测试,以便可以用 一个'virgin'对象来调用它们em>或与它的克隆?你如何测试部分克隆是否不够深 - 因为这只是一种可以在以后发现可怕的错误的问题?

6 个答案:

答案 0 :(得分:2)

您的测试方法取决于您提出的解决方案类型。如果您编写一些自定义克隆代码并且必须在每个可克隆类型中手动实现它,那么您应该真正测试每种类型的克隆。或者,如果您决定采用更通用的路径(上述反射可能适合),您的测试只需要测试克隆系统必须处理的特定方案。

回答您的具体问题:

  

您是否为该类编写(或一旦发现克隆需要时重写)所有单元测试,以便可以使用'virgin'对象或克隆它来调用它们?

您应该对可以在原始对象和克隆对象上执行的所有方法进行测试。请注意,设置一个简单的测试设计以支持这一点应该非常容易,而无需手动更新每个测试的逻辑。

  

你如何测试部分克隆是否不够深 - 因为这只是一种可以在以后发现可怕的错误的问题?

这取决于您选择的克隆方法。如果必须手动更新可克隆类型,则应测试每种类型是否克隆所有(并且仅)您期望的成员。然而,如果您正在测试克隆框架,我会创建一些测试可克隆类型来测试您需要支持的每个场景。

答案 1 :(得分:2)

有一个非常明显的解决方案,并不需要那么多的工作:

  1. 将对象序列化为二进制格式。
  2. 克隆对象。
  3. 将克隆序列化为二进制格式。
  4. 比较字节。
  5. 假设序列化有效 - 而且因为你使用它来克隆它更好 - 这应该很容易维护。实际上,它将完全封装在对类结构的更改中。

答案 2 :(得分:1)

我只是编写一个测试来确定克隆是否正确。如果类没有密封,您可以通过扩展它来为它创建一个线束,然后在子类中公开所有内部。或者,您可以使用反射(yech),或使用MSTest的Accessor生成器。

您需要克隆对象,然后浏览对象所具有的每个属性和变量,并确定它是否已正确复制或正确克隆。

答案 3 :(得分:1)

我喜欢编写使用原始和克隆对象上的内置序列化程序之一的单元测试,然后检查序列化表示是否相等(对于二进制格式化程序,我只能比较字节数组)。这在对象仍然可序列化的情况下非常有用,而且我只是因为性能而改为自定义深度克隆。

此外,我喜欢使用类似这样的

为我的所有Clone实现添加调试模式检查
[Conditional("DEBUG")]
public static void DebugAssertValueEquality<T>(T current, T other, bool expected, 
                                               params string[] ignoredFields) {
    if (null == current) 
    { throw new ArgumentNullException("current"); }
    if (null == ignoredFields)
    { ignoredFields = new string[] { }; }

    FieldInfo lastField = null;
    bool test;
    if (object.ReferenceEquals(other, null))
    { Debug.Assert(false == expected, "The other object was null"); return; }
    test = true;
    foreach (FieldInfo fi in current.GetType().GetFields(BindingFlags.Instance)) {
        if (test = false) { break; }
        if (0 <= Array.IndexOf<string>(ignoredFields, fi.Name))
        { continue; }
        lastField = fi;
        object leftValue = fi.GetValue(current);
        object rightValue = fi.GetValue(other);
        if (object.ReferenceEquals(null, leftValue)) {
            if (!object.ReferenceEquals(null, rightValue))
            { test = false; }
        }
        else if (object.ReferenceEquals(null, rightValue))
        { test = false; }
        else {
            if (!leftValue.Equals(rightValue))
            { test = false; }
        }
    }
    Debug.Assert(test == expected, string.Format("field: {0}", lastField));
}

此方法依赖于在任何嵌套成员上准确实现Equals,但在我的情况下,任何可克隆的东西也是等同的

答案 4 :(得分:1)

我通常会实现Equals()来深入比较这两个对象。您可能不需要在生产代码中使用它,但它可能在以后会派上用场,并且测试代码更清晰。

答案 5 :(得分:0)

以下是我如何实施这一过程的示例,尽管这需要针对该场景进行定制。在这种情况下,我们有一个讨厌的对象链,可以很容易地改变,克隆被用作一个非常关键的原型实现,所以我不得不一起修补(破解)这个测试。

public static class TestDeepClone
    {
        private static readonly List<long> objectIDs = new List<long>();
        private static readonly ObjectIDGenerator objectIdGenerator = new ObjectIDGenerator();

        public static bool DefaultCloneExclusionsCheck(Object obj)
        {
            return
                obj is ValueType ||
                obj is string ||
                obj is Delegate ||
                obj is IEnumerable;
        }

        /// <summary>
        /// Executes various assertions to ensure the validity of a deep copy for any object including its compositions
        /// </summary>
        /// <param name="original">The original object</param>
        /// <param name="copy">The cloned object</param>
        /// <param name="checkExclude">A predicate for any exclusions to be done, i.e not to expect IPolicy items to be cloned</param>
        public static void AssertDeepClone(this Object original, Object copy, Predicate<object> checkExclude)
        {
            bool isKnown;
            if (original == null) return;
            if (copy == null) Assert.Fail("Copy is null while original is not", original, copy);

            var id = objectIdGenerator.GetId(original, out isKnown); //Avoid checking the same object more than once
            if (!objectIDs.Contains(id))
            {
                objectIDs.Add(id);
            }
            else
            {
                return;
            }

            if (!checkExclude(original))
            {
                Assert.That(ReferenceEquals(original, copy) == false);
            }

            Type type = original.GetType();
            PropertyInfo[] propertyInfos = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
            FieldInfo[] fieldInfos = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);

            foreach (PropertyInfo memberInfo in propertyInfos)
            {
                var getmethod = memberInfo.GetGetMethod();
                if (getmethod == null) continue;
                var originalValue = getmethod.Invoke(original, new object[] { });
                var copyValue = getmethod.Invoke(copy, new object[] { });
                if (originalValue == null) continue;
                if (!checkExclude(originalValue))
                {
                    Assert.That(ReferenceEquals(originalValue, copyValue) == false);
                }

                if (originalValue is IEnumerable && !(originalValue is string))
                {
                    var originalValueEnumerable = originalValue as IEnumerable;
                    var copyValueEnumerable = copyValue as IEnumerable;
                    if (copyValueEnumerable == null) Assert.Fail("Copy is null while original is not", new[] { original, copy });
                    int count = 0;
                    List<object> items = copyValueEnumerable.Cast<object>().ToList();
                    foreach (object o in originalValueEnumerable)
                    {
                        AssertDeepClone(o, items[count], checkExclude);
                        count++;
                    }
                }
                else
                {
                    //Recurse over reference types to check deep clone success
                    if (!checkExclude(originalValue))
                    {
                        AssertDeepClone(originalValue, copyValue, checkExclude);
                    }

                    if (originalValue is ValueType && !(originalValue is Guid))
                    {
                        //check value of non reference type
                        Assert.That(originalValue.Equals(copyValue));
                    }
                }

            }

            foreach (FieldInfo fieldInfo in fieldInfos)
            {
                var originalValue = fieldInfo.GetValue(original);
                var copyValue = fieldInfo.GetValue(copy);
                if (originalValue == null) continue;
                if (!checkExclude(originalValue))
                {
                    Assert.That(ReferenceEquals(originalValue, copyValue) == false);
                }

                if (originalValue is IEnumerable && !(originalValue is string))
                {
                    var originalValueEnumerable = originalValue as IEnumerable;
                    var copyValueEnumerable = copyValue as IEnumerable;
                    if (copyValueEnumerable == null) Assert.Fail("Copy is null while original is not", new[] { original, copy });
                    int count = 0;
                    List<object> items = copyValueEnumerable.Cast<object>().ToList();
                    foreach (object o in originalValueEnumerable)
                    {
                        AssertDeepClone(o, items[count], checkExclude);
                        count++;
                    }
                }
                else
                {
                    //Recurse over reference types to check deep clone success
                    if (!checkExclude(originalValue))
                    {
                        AssertDeepClone(originalValue, copyValue, checkExclude);
                    }
                    if (originalValue is ValueType && !(originalValue is Guid))
                    {
                        //check value of non reference type
                        Assert.That(originalValue.Equals(copyValue));
                    }
                }
            }
        }
    }