【问题标题】:How to Perform Unit testing for Serialization and Deserialization of a class in C#?如何在 C# 中对类的序列化和反序列化执行单元测试?
【发布时间】:2017-03-31 19:57:57
【问题描述】:

我想对一个类执行 NUnit 或 MS 测试以了解序列化和反序列化行为。

我查看了另一篇stackoverflow文章here,但我仍然不明白如何做到这一点。请帮助我了解如何执行这些测试,

以下是我的部分代码:

namespace PMT.Service.Common.DataContract
{
    public partial class MyBankInfo
    {
        public string MyId { get; set; }
        public string MyAccountNumber { get; set; }
        public string MyAccountType { get; set; }
        public string MyBankName { get; set; }
        public string MyBankBranchName { get; set; }
        public string MyBankCity { get; set; }
        public string MyBankCityPincode { get; set; }
        public string MyBankIFSCCode { get; set; }

        public void Serialize(BinaryStreamWriter binaryStreamWriter)
        {           
            binaryStreamWriter.Write(MyId);
            binaryStreamWriter.Write(MyAccountNumber);
            binaryStreamWriter.Write(MyAccountType);
            binaryStreamWriter.Write(MyBankName);
            binaryStreamWriter.Write(MyBankBranchName);
            binaryStreamWriter.Write(MyBankCity);
            binaryStreamWriter.Write(MyBankCityPincode);
            binaryStreamWriter.Write(MyBankIFSCCode);
        }

        public bool Deserialize(BinaryStreamReader binaryStreamReader,out   string errorString)
        {
            errorString = string.Empty;
            try
            {
                MyId = binaryStreamReader.ReadString();
                MyAccountNumber = binaryStreamReader.ReadString();
                MyAccountType = binaryStreamReader.ReadString();
                MyBankName = binaryStreamReader.ReadString();
                MyBankBranchName = binaryStreamReader.ReadString();
                MyBankCity = binaryStreamReader.ReadString();
                MyBankCityPincode = binaryStreamReader.ReadString();
                MyBankIFSCCode = binaryStreamReader.ReadString();

            }
            catch (Exception ex)
            {
                errorString = ex.Message;
            }
            return string.IsNullOrEmpty(errorString);
        }
    }
}

【问题讨论】:

标签: c# unit-testing serialization nunit


【解决方案1】:

有两种方法可以测试序列化和反序列化:单独或同时测试。

如果序列化数据是由您无法控制的其他软件创建或使用的,则最好进行单独测试。在这种情况下,必须验证确切的格式。这也是一个难点。

如果您的数据仅由您自己的类进行序列化和反序列化,那么您可以同时测试两者:

  1. 创建测试对象
  2. 在内存中或在磁盘上创建 Writer。
  3. 序列化给那个作者。
  4. 创建第二个对象并从保存的数据中反序列化它。
  5. 编写一组断言,将原始对象的属性与新对象的属性进行比较。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-26
    • 2015-05-18
    • 2012-03-29
    相关资源
    最近更新 更多