Has anyone created a DataContract testing tool?

前端 未结 2 670
一生所求
一生所求 2020-12-29 09:20

Has anyone seen a library that tests WCF DataContracts? The motivation behind asking this is that I just found a bug in my app that resulted from my not annotating a propert

相关标签:
2条回答
  • 2020-12-29 09:45

    It's simple enough to use DataContractSerializer to serialise your object to a MemoryStream, then deserialise it back into existence as a new instance.

    Here's a class that demonstrates this round-trip serialisation:

    public static class WcfTestHelper
    {
        /// <summary>
        /// Uses a <see cref="DataContractSerializer"/> to serialise the object into
        /// memory, then deserialise it again and return the result.  This is useful
        /// in tests to validate that your object is serialisable, and that it
        /// serialises correctly.
        /// </summary>
        public static T DataContractSerializationRoundTrip<T>(T obj)
        {
            return DataContractSerializationRoundTrip(obj, null);
        }
    
        /// <summary>
        /// Uses a <see cref="DataContractSerializer"/> to serialise the object into
        /// memory, then deserialise it again and return the result.  This is useful
        /// in tests to validate that your object is serialisable, and that it
        /// serialises correctly.
        /// </summary>
        public static T DataContractSerializationRoundTrip<T>(T obj, 
                        IEnumerable<Type> knownTypes)
        {
            var serializer = new DataContractSerializer(obj.GetType(), knownTypes);
            var memoryStream = new MemoryStream();
            serializer.WriteObject(memoryStream, obj);
            memoryStream.Position = 0;
            obj = (T)serializer.ReadObject(memoryStream);
            return obj;
        }
    }
    

    Two tasks that you are responsible for:

    • Populating the instance in the first place with sensible data. You might choose to use reflection to set properties or supply a constructor with its arguments, but I've found this approach just won't work for anything other than incredibly simple types.
    • Comparing the two instances after you have round-trip de/serialised it. If you have a reliable Equals/GetHashCode implementation, then that might already be done for you. Again you might try using a generic reflective comparer, but this mightn't be completely reliable.
    0 讨论(0)
  • 2020-12-29 09:50

    A better approach: create a proxy that serializes/deserializes all arguments when calling a method. Code can be found here: http://mkramar.blogspot.com/2013/01/unit-test-wcf-with-serialization.html

    0 讨论(0)
提交回复
热议问题